3

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.

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for the links, I find it easiest to learn from good examples
2

I'm using jquery and I used to do like this in my PHP (if using json):

<?php
$var = 'stuff';
echo '{"var":"'.$var.'"}';
?>

it would return to a json.

and the ajax :

$.ajax({
url : "mysite.com/test.php",
dataType : "json",
data :"",
type : "POST",
success : 
function (data){
alert(data.var);
}
});

(data and type in the ajax are not needed if you just want to get json from "mysite.com/test.php");

1 Comment

thanks, does it have to print out on the page if directly accessed in a browser?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.