Sometimes you need to fetch some information from another site

There are many solutions but the most common an elegant  is use jQuery and Ajax.

But there is a problem: the communication between two different domain is blocked by default.

I have found the solution in this article by Ravishanker Kusuma and I reported here as back up.


In this tutorial, I explained how to send Cross Domain AJAX Requestwith jQuery and PHP. Different methods of handling cross domain AJAX requests are covered in this article.

Cross-domain AJAX request is possible in two ways
1). Using JSONP
2). Using CORS (Cross-origin resource sharing)

1).USING JSONP

We can send cross domain AJAX requests using JSONP. Below is the simple JSONP Request:

 
 
  1.  $.ajax({
  2.      url: "http://hayageektest.appspot.com/cross-domain-cors/jsonp.php",
  3.      dataType: "jsonp",
  4.  });
  5.  function mycallback(data) {
  6.      alert("Here: " + data.name);
  7.  }

jsonp.php response is:

 
 
  1. mycallback({"name":"Ravishanker","age":32,"location":"India"})

when the JSONP request is successful, mycallback function is called.

If you want the function handling automatically, you can use the below approach. In this case, you need not have any extra function. You can get the server response in success callback

 
 
  1. $.ajax({
  2.     url: "http://hayageektest.appspot.com/cross-domain-cors/jsonp.php",
  3.     dataType: "jsonp",
  4.     jsonp: "mycallback",
  5.     success: function(data) {
  6.         alert("Name:" + data.name + "nage:" + data.age + "nlocation:" + data.location);
  7.     }
  8. });

jsonp.php source code:

 
 
  1. <?php
  2.     $callback ='mycallback';
  3.  
  4.     if(isset($_GET['mycallback']))
  5.     {
  6.         $callback = $_GET['mycallback'];
  7.     }   
  8.     $arr =array();
  9.     $arr['name']="Ravishanker";
  10.     $arr['age']=32; 
  11.     $arr['location']="India";   
  12.  
  13.     echo $callback.'(' . json_encode($arr) . ')';
  14.  
  15. ?>

This works in all the browsers but the problem is: JSONP supports only GET method. POST method is not allowed.

[DEMO]

You can read here the rest of article…