JSONP cross-domain ajax call with jquery

→ Are you a new visitor? Please visit the page guidance for new visitors ←

JSONP cross-domain ajax call with jquery

This was killing me back in the past. Imagine the following situation. You are on domain abc.com, and you want to make a request to domain xyz.com to get some data or whatever. To do so, you need to cross domain boundaries, which is a DO-NOT in the world of web. The one item that surpass this limitation is <script> tags. When you use a script tag, the domain limitation is ignored, but under normal circumstances, you can’t really do anything with the results, the script just gets evaluated and this doesn’t help you very much.

JSONP to the rescue.

JSONP works by constructing a “script” element (either in HTML markup or inserted into the DOM via JavaScript), which requests to a remote data service location. The response is a javascript loaded on to your browser with name of the pre-defined function along with parameter being passed that is the JSON data being requested. When the script executes, the function is called along with JSON data, allowing the requesting page to receive and process the data.

For further reading about JSONP go to The secret behind jsonp.

When you make your request to a server that is JSONP enabled, you pass a special parameter that tells the server a little bit about your page. That way, the server is able to nicely wrap up its response in a way that your page can handle.

For example, say the server expects a parameter called “callback” to enable its JSONP capabilities. Then your request would look like:

Without JSONP, this might return some basic javascript object, like so:

However, with JSONP, when the server receives the “callback” parameter, it wraps up the result a little differently, returning something like this:

As you can see, it will now invoke the method you specified. So, in your page, you define the callback function:

And now, when the script is loaded, it’ll be evaluated, and your function will be executed. And you obtain cross-domain requests!

Example code (client side)

Code (server side)

As you can see above, first we allow all types of cross domain requests on our server side file. After that we get the callback function name that you are building it on client side and call it with some parameters on server side.

 

Request an article ←