Last Updated: February 25, 2016
·
11.32K
· ernestocodesnippets

jQuery Ajax Cross Domain

Hate it when you can't send ajax requests cross domain?
A solution could be to use JSONP.

Let's take an example, a bookmarklet that user can click on any site and sends a request to your serverside. Normally this wouldn't be allowed.

Using jQuery you could write something like this:

$.ajax({
  url:"script.php" + "?data=mydata&callback=mycallback",
  dataType: "jsonp',
  success: function(data) {
    alert(data);
  }
});

what we have done here is type in our url string, added paramaters to the url like the data, and most importantly we have added a callback parameter with the name of our callback in this case mycallback, notice we have set the dataType to 'jsonp' this is very important

if we were to run this with the following php code on the server side:

<?php
$data = $_GET["data"];
echo "data received";
return;
?>

We would in fact now send the request to our server and it would parse and run the php script or whatever, but if we return anything to the script, like a status update to the user, we would get an error, xhr request error method shows us that it is a parse error, to fix this all we need to do is wrap the data we are returning to the script in between our callback function we mentioned in our url parameter:

<?php
$data = $_GET["data"];
$callback = $_GET["callback"];
echo $callback . "(" . "data received" . ")";
return;
?>

This will now work, you get the data you wanted cross domain.
This is just a hack, allowing ajax crossdomain, jsonp is capable of many other things, check this link out if you want to learn more:

http://remysharp.com/2007/10/08/what-is-jsonp/

1 Response
Add your response

You might also look at CORS (https://developer.mozilla.org/en-US/docs/HTTP_access_control) which allows you to make cross domain AJAX requests using any method (instead of being limited to GET with JSONP). CORS support (via pollyfill) is available back to IE 8.

over 1 year ago ·