Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Javascript to receive variable from remote php file?

I need to retrieve a variable from a remote php file using javascript. I'm doing this using phonegap so same origin policy doesn't apply. I guess I need to use json / ajax but I can't find any tutorials that show me how to do this.

Is it as simple as having this in a php file:

<?php
    $var = 'stuff';
    echo json_encode( $var );
?>

And something like this in my application:

 $.getJSON('mysite.com/test.php', function( data ) {
                           $.each( data, function( i, entry ) {
                              alert( entry );
                           });

Or is this totally the wrong approach? Any help would be great, thanks.

like image 286
mao Avatar asked May 12 '26 02:05

mao


1 Answers

so for starters here are the docs on JQuery's ajax & the docs for JQuery's getJSON; and finally a slightly dated but decent tutorial explaining the basics on how to get started with raw .JSON files.

typically when I am dealing with JSON i am interacting with a web API; and most of the time they are RESTful api's at that... creating one is slightly more complex than what you have there but your thought process is on track.

here is a working access point to the google finance stock quotes api running a query on microsoft:

http://finance.google.com/finance/info?client=ig&q=MSFT

and an example of a json call (using jsonp for accessing an external url):

$.ajax({
  url: 'http://finance.google.com/finance/info?client=ig&q=MSFT',
  dataType: 'jsonp',
  success: function(data){
    console.log( data );
  }
});

to make things easier i would try and break the work into two steps... first get a handle on accepting data from a api you know is functioning (ie google finance above)... and then move on to the next step of trying to write your own WebAPI in php (eg say you wanted to build your "variable" into a database or something a bit more useful than a flat php file). this way you can debug a bit easier with less hair loss

like image 192
Joe Avatar answered May 13 '26 14:05

Joe



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!