Cross Domain JSONP with jQuery

June 27, 2014

Modern browsers do not allow cross domain AJAX calls due to security restrictions, or the "Same-Origin Policy". In other words, all AJAX requests made from a webpage must be directed at a URL on the same domain as the webpage itself.

There is a way around this, namely through the fact that browsers do not enforce the Same-Origin Policy on <script> tags and through a technique called JSONP. JSONP uses normal JSON formatted data with "P"adding, or a prefix that wraps the JSON data from an AJAX request in a function call that is callable by the originating webpage.

You can read about the gory details of JSONP but the good news is that JSONP is dead simple to implement with jQuery.

The first thing is to start out with some JSON data that is returned by the different-domain server. For example, http://different-domain.com/mydata.json

{
    "some": "data",
    "some more": "data"
}

Next, this data should be modified so it is wrapped in a function call. Yes, you will either need access to this server to properly wrap the JSON data, or be using a JSONP-compliant 3rd-party web API.

functionName(
{
    "some": "data",
    "some more": "data"
});

However, when jQuery sends the JSONP AJAX request (we'll get to this in a minute), it uses a temporary function name, which is passed via a get parameter to the different domain server, e.g. http://different-domain.com/mydata.json?callback=jqueryTempFunctionName. Of course jqueryTempFunctionName will not be called that as it will be a random name made up by jQuery and not of concern to the programmer. So constructing the JSON then becomes a matter of using this function name taken from the request.

<?php
...
...
echo $_GET["callback"] . "(" . json_encode($whatever) . ");";

Now, on to the requesting webpage (jQuery). Let's call this page http://my-domain.com/mywebpage.html. To make use of this JSONP service we just set up, first include jQuery at the bottom of your page before your own Javascript. For the latest version of jQuery:

...
...
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script src="/js/myscript.js" type="text/javascript"></script>
</body>
</html>

Be careful when using the latest version as some functionality may have changed. The Google-hosted specific versions of jQuery will always work well.

...
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="/js/myscript.js" type="text/javascript"></script>
</body>
</html>

Now, set up your AJAX request in your myscript.js file. You can also read more about the jQuery .ajax() function.

$(function() {
   $.ajax({ url: 'http://different-domain.com/mydata.json',
            dataType: 'jsonp',
            success: function(json) {
                // do something with the json variable here
                // it represents all of the json that we wrapped in a function call in the step above 
        }}).done(function() {
                // ...
        }).fail(function() {
                // ...
        }).always(function() {
                // ...
        }); 
});

The important thing to remember here is that the dataType parameter must be 'jsonp' (all lower-case). jQuery will then tack on a ?callback=jqueryTempFunctionName to the end of the url. Once again, remember that jqueryTempFunctionName is only an example in this post and jQuery will make up its own temporary callback function name.

If all goes well you should have the cross-domain JSON returned as a function parameter to the success callback.

 

comments powered by Disqus

About This Site

This site was designed by We Are How.

This site is powered by Sculpin static site generator and the source is available here.

Yotta = 10^24, or 1 000 000 000 000 000 000 000 000, the largest metric prefix.


Contact

Get in touch to find out how we can help you refine your vision and implement a dynamite product that will help your business grow. Our agile product development process is thoughtfully designed to give clients ongoing feedback and visibility from project inception to completion.