2

I have my php coded page on one server that returns a json result. php file called: getInfoData.php and the return is as below.

  echo json_encode($v);

No I can use $.getJSON(??) to read the json and run it all on the same sever fine, but I need the php page to be on a different sever than the js page calling it.

But then I get then when I do I get the cross domain issue.

So I changed the code to use the following (jsonp):

  $.ajax({
    url: 'FILE_LOCATION_ON_ANOTHER_SERVER',
    type: 'GET',
    crossDomain: true,
    dataType: 'jsonp',
    success: function() { console.log("Success"); },
    error: function() {console.log('Failed!'); }
});

but I do not see anything I just get the following with my console:

  http://www.THEURL.com/FOLDER/FILENAME.php?callback=jQuery171013088115444406867_1332256223342&_=1332256223343

and a message saying failed!.

What am I doing wrong and how if at all can I fix this?

Thanks

gen_Eric
  • 223,194
  • 41
  • 299
  • 337
Simon Davies
  • 3,668
  • 9
  • 41
  • 69

2 Answers2

3

JSONP isn't actually JSON. It's a bit of a "hack". JSONP is actually a JavaScript file, that gets downloaded and ran.

In your PHP page, you should be passed a callback parameter. You need to "wrap" your JSON in it. It should look like this:

func({json: data})

So, your PHP should look like this:

echo $_GET['callback'] . '(' . json_encode($v) . ')';
gen_Eric
  • 223,194
  • 41
  • 299
  • 337
2

I use this usually but maybe there is a better way

<?php header('content-type: application/javascript; charset=utf-8');

$data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);

echo htmlspecialchars($_GET['callback']) . '('.json_encode($data).')';

since i saw you provided a callback parameter everything should be ok

kungfooman
  • 4,473
  • 1
  • 44
  • 33
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192