jQuery and jsonp (cross-domain requests in jQuery)
- February 12th, 2011
- Posted in articles
- By Ionut
- Write comment
As we know AJAX is a great tool in making very nice and interactive web applications, but one of it’s drawbacks is the fact that with AJAX we can’t do cross-domain requests because of restrictions imposed by the browser (same-origin policy). To solve this problem one of the most simple and scalable solutions is to insert a script element in the page (the script element is not restricted by the same-origin policy) and get the required data this way. To make this solution easy-to-use, JSON format is used to return the data wrapped in a function call.
So JSONP is a script tag injection, passing the response from the server in to a user specified function by using the JSON data format.
Ok..so let’s say we would like to make a cross-domain using jQuery. Here is how the jQuery $.ajax call should look like:
-
$.ajax({
-
dataType: 'jsonp',
-
data: 'id=test',
-
jsonp: 'jsonp_callback',
-
url: 'http://www.differentdomain.com/get_data.php',
-
success: function () {
-
// do something
-
},
-
});
So we use the simple $.ajax method from jQuery, but we add the jsonp attribute with the value “jsonp_callback”. What this will do is add to the request that we do a parameter that is the function that the script should return the JSON data wrapped in… so the http://www.differentdomain.com/get_data.php would get at the end &jsonp_callback=xxx where xxx will be a dynamicaly generated function by jQuery(something like jsonpcallback123456)
Now on the server side (in the get_data.php file) we have to get the callback name and send the data in JSON format wrapped in the callback function.
Something like this:
-
<?php
-
$jsonp_callback = $_GET['jsonp_callback'];
-
$data = array('1','2','3');
-
echo $jsonp_callback . '('.json_encode($data).');';
-
?>
Cheers!
You saved my day!
Thank you for your helps.