jQuery and JSONP for Cross Domain Requests


If you have ever had issues making AJAX calls between two servers (domains) then I strongly suggest you check out this post and jQuery ajax method.

I went through a considerable amount of headbanging before finally figuring this out and the post above is the only solution I could find that even came close to pointing me in the right direction. One thing I would add to the post above is a clearer example. Here was my solution:

function makeRequest() {
$.ajax({
url: ‘http://myserver.com/page.php’,
dataType: ‘jsonp’,
jsonp: ‘jsonp_callback’,
data: “id=10″
});
}

This function will generate a request to page.php on http://myserver.com (you should replace the domain and PHP script location with your own of course).

In my PHP script, and after doing the necessary processing, I returned the following:

echo ‘processResponse(’ . json_encode($vRetValue) . ‘)’;

When this is received by the AJAX call above the processResponse function will be called.

function processResponse(data) {
// do something with the data
}

Note: Make sure your call back function is outside of any jQuery.ready blocks:

$().ready(function() {
// stuff here
});

function callbackFunction() {
// do stuff here
}


Tuesday, February 9th, 2010 Posted in Development, Technology | No Comments »