Thursday, May 13, 2010

Cross-Domain AJAX with Jquery and JSONP

I've had a heck of a time recently doing some cross-domain ajax scripting with json. This is for an iPhone website and it's basic HTML (no PHP) and it needs to access some data from a specific website. At first we tried JQuery.post, but to no avail.

Eventually we realized that we would need to use JSONP. JSONP requires you to do things on the client side as well as the server side. We use CakePHP here at rain, so you will see that in the server code.

On the client side, as far as I can tell, POST is not an option, so use .getJSON instead

This is the client side code:
var data = $("form").serialize();
$.getJSON("http://mytest.url.com/services/server?callback=?", data, function(data) {
alert(data);
});

Here is the server side:
echo $this->params['url']['callback'] . '(' . json_encode($data) . ');';

Two helpful articles on the subject:
http://remysharp.com/2007/10/08/what-is-jsonp/
http://www.markhneedham.com/blog/2009/08/27/jquery-post-jsonp-and-cross-domain-requests/

No comments:

Post a Comment