Cross Domain Ajax Call

Method : JSONP

Description :  Are you looking for the code that will call file of other server than you are at right place just follow below instruction step by step it will work for you .

Steps :

1] Create one javascript function name it as “AjaxCallForOtherDomain”.

function AjaxCallForOtherDomain()

{

               var ajax_file_url = http://www.otherdomain.com/ajax/callme.php;

               var params = “&id=5”;

               $.getJSON(ajax_file_url+params+"&jsoncallback=?",    function(data){

               $('#placeholder').append(data.resultdata);

              });

}

** ajax_file_url is the web file url that we suppose to call.

** params is the variable that we are going to pass in php files.

** jsoncallback is the variable that will be dynamically assigned by “getJSON” function so you will get parameter “jsoncallback” parameter that will be function while you respond in PHP file.

** placeholder is the id where i will append my result from that is response from server file.

** data is JSON array.

** data.resultdata : Here result data is node of data array. E.g. : $data[‘resultdata’];

2] Create one PHP file on other domain inside ajax folder. 

Suppose you have created the file on www.otherdomain.com/publichtml/ajax/callme.php

<?php

$ jsoncallback = $_REQUEST[‘jsoncallback’];

echo  $ jsoncallback.”( {" resultdata’": "sudhirstiwari"} )”;
Exit;

?>

3] Handle the call in your javascript function inside the response.

$.getJSON(ajax_file_url+params+"&jsoncallback=?",    function(data){

// example of what is received from the server...

$(‘#placeholder’).append(data.resultdata);

});

That’s it :)
Its very easy so let me know if you have any queries regarding this .
Have a good luck…



4 comments

add comment
sadamusic.com (4 years ago)

I try this but it was not work for me. I want to call a php page on other server don’t know about its input or output but simply wish to include in my script via java script. Could you help me in this.

    Sudhir Tiwari Sudhir Tiwari (4 years ago)

    Can you please provide me the sample the code that you are using. Bcoz above is working nice. But make sure the output is in well formatted json array. It must not have any special characters in between otherwise the json may be borken.

sadamusic.com (4 years ago)

I try the above code with simple output echo ‘sadamusic.com’ but it doesn’t show, it show only blank page.

function AjaxCallForOtherDomain()

{

var ajax_file_url = http://www.otherdomain.com/ajax/callme.php;

var params = “&id=5”;

$.getJSON(ajax_file_url+params+”&jsoncallback=?”, function(data){

$(‘#placeholder’).append(data.resultdata);

});

}

same code I use for display data. with div id placeholder.

Thanks in advance.

sadamusic.com (4 years ago)

Could you send me a file at info@sadamusic.com??

Leave Comment

*