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. let’s say we would like to make a cross-domain using jQuery. Here is how the jQuery $.ajax call should look like:

  1. $.ajax({
  2.   dataType: 'jsonp',
  3.   data: 'id=test',
  4.   jsonp: 'jsonp_callback',
  5.   url: '',
  6.   success: function () {
  7.     // do something
  8.   },
  9. });

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 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:

  1. <?php
  2. $jsonp_callback = $_GET['jsonp_callback'];
  3. $data = array('1','2','3');
  4. echo $jsonp_callback . '('.json_encode($data).');';
  5. ?>