• Blog
  • Home
  • Blog
    • Medoo: the lightest PHP database framework
    • Deploy your code Everywhere
    • How to Send Cross Domain with AJAX

How to Send Cross Domain with AJAX

Monday, October 26th 2020
  • cross-site.png

Sometimes you need to fetch some information from another site. There are many solutions, but the most common is to use jQuery and Ajax.

But there is a problem: the communication between two different domains 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)

USING JSONP

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

$.ajax({
    url: "http://hayageektest.appspot.com/cross-domain-cors/jsonp.php",
    dataType: "jsonp",
});

function mycallback(data) {
    alert("Here: " + data.name);
}

jsonp.php response is:

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

When the JSONP request is successful, the 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

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

jsonp.php source code:

<?php
    $callback ='mycallback';

    if(isset($_GET['mycallback']))
    {
        $callback = $_GET['mycallback'];
    }   
    $arr =array();
    $arr['name']="Ravishanker";
    $arr['age']=32; 
    $arr['location']="India";   

    echo $callback.'(' . json_encode($arr) . ')';

?>

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

You can read here the rest of the article…

  • © 2021 Gekode
Gekode Ltd - Company No: 08042020