There are lots of cases around the web dealing with cross-domain Ajax using  JQuery. The main problem when calling an endpoint that is located in another domain is that browsers block them by the name of "same origin policy". While this is a security measure for blocking XSS, it's a pain the neck of a developer who repeatedly was said that REST and JSON are cool and easy. Fortunately there are some workarounds for that.

First, It's better to get the latest version of JQuery from here. From version 1.5 some new attributes added to make cross-domain calls easier.

There are some different request calls available such as .load(), .get(), .post(), .getJSON(), and .Ajax(). It's better to use .Ajax() call as it provides you with high level of flexibility.

The simple Ajax call can be something like the following:

Fortunately, it accepts different data types such as html, text, json, xml, script, and jsonp. In order to call the a function in another domain the trick is to use jsonp or json with padding. In this way, the server wraps json data in a javascript function. This is the function that will be called (callback) when the response comes back to client and it actually automatically points to the success method in our example above.

There are three changes to make it happen:

crossDomain attribute simply force the request to be cross-domain. dataType is jsonp and there is a parameter added to the url. When this call is triggered, the question mark will be replaced with a random method name like jsonp474639_1234757. This is the name of callback method that will be called when the response comes back to the client.

jsonp474639_1234757({"first_name": "Smithson"})

Remarks:

Some servers do not send back the correct content-type. In these cases javascript engine triggers a warning but the operation should continue as usual.

If the server only returns the Json payload, it needs to check for the callback parameter as well. If it exists, it should wrap the payload inside the callback name: callback(Json payload); and returns the value.