1

I'm aware that modern browsers don't allow AJAX requests to foreign URLS, The workaround is JSON encoding and I'm doing that like this:

 function findZipCodesInRadius(userZip, radiusInMiles) {

     $.getJSON("http://mydomain.com/php/zipCodesInRadius.php?callback=?", {
         TheUserZip: userZip,
         TheRadiusInMiles: radiusInMiles
     },

     function (data) {
         alert("Data Loaded: " + data);
     });


 }

and on the PHP side of things I have it "echoing" the results back like this:

$JSONData = array("callback"=>"true"); 
echo json_encode($JSONData); 

After looking around google, the above code is what I've found and it's still not working. How do I properly echo the callback? Maybe I'm doing the ajax request incorrectly? I usually do it a different way, but because I'm trying to access a file on another website of mine, I've been looking everywhere on the proper way of sending the request and this is what I came up with. Not sure what I'm doing wrong.

Silas
  • 582
  • 2
  • 9
  • 19

3 Answers3

2

You will need to implement a callback function in order for this to work. You will need to wrap your json_encode with the callback function which is defined in $_GET['callback'].

For example, echo $_GET['callback']."(".json_encode($JSONData).")";.

Ryan Tse
  • 1,559
  • 11
  • 15
  • Can't thank you enough. It was driving me crazy! Totally makes sense now. It will allow me to accept this answer in 5 minutes. – Silas Jan 24 '13 at 08:21
1

You have to add the callback for jsonp requests

$JSONData = array("callback"=>"true");
$callback = $_GET['callback'];
echo $callback,'(',json_encode($JSONData),')'; 
Musa
  • 96,336
  • 17
  • 118
  • 137
1

I'm aware that modern browsers don't allow AJAX requests to foreign URLS,

On the contrary, modern browsers allow that, if you tell them to (see CORS)

The workaround is not JSON encoding but JSONP, a technique that uses dynamic <script> elements to load the external source. For this to work, the source must be executable JavaScript, this is where the callback parameter comes into play:

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

The parameter will be a function name, but you don't have to care about that in your JS code, JQuery.getJSON handles it for you transparently.

Fabian Schmengler
  • 24,155
  • 9
  • 79
  • 111