AJAX and JSON cross-domain calls from PhoneGap application

This is just as quick as possible example on getting you to the subject, without unnecessary blah, blah. Only pure detail on how to sent AJAX / JSON calls (cross-domain!) from your PhoneGap application. With references to other intresting and more comprehensive sources in the end.

BTW: You don’t even need a response server ready to get started! Example is based on JSON Test — Simple testing for JSON-based applications service.

This article assumes that you’re using jQuery in PhoneGap application.

OK, let’s get to work. First, we need an initiator:

<p>
    <a id="ipButton" class="btn btn-inverse" href="#"><i class="icon-random icon-white"></i> IP Address</a>
    <a id="md5Button" class="btn btn-primary" href="#"><i class="icon-cog"></i> MD5</a>
</p>

If you’re using Twitter Bootstrap, above will render as pretty-looking buttons. If not, all the classes will be ignored and you should end up with pure links.

Now, the code:

jQuery(function($)
{
    $('body').on('click', '#ipButton', function()
    {
        $.ajax
        ({
            type : "GET",
            dataType : "jsonp",
            url : 'http://ip.jsontest.com/',
            data : {},
            success: function(data)
            {
                alert('Your IP Address is: ' + data.ip);
            },
            error: function()
            {
               alert('There was an error loading the data!');
            }
        });
    });
    
    $('body').on('click', '#md5Button', function()
    {
        var string = prompt('Enter ANY text');
        
        if (string !== null && string !== '')
        {
            $.ajax
            ({
                type : "GET",
                dataType : "jsonp",
                url : 'http://md5.jsontest.com/?text=' + string,
                data : {},
                success: function(data)
                {
                    prompt('MD5 hash of "' + data.original + '" is: ', data.md5);
                },
                error: function()
                {
                   alert('There was an error loading the data!');
                }
            });            
        }
    });
});

And that is all. You can run this directly in your desktop computer browser or use PhoneGap Build, to compile this as a part of mobile application.

Note, that we’re using JSONP (JSON packaged) type calls, so this is safe (and works!) even cross-domain. You may run it from your localhost and it will also work in your PhoneGap application, even though that both of these domains are not the same as jsontest.com service’s domain.

Note also, that above presented example code could, of course, be much simpler. I wrote this like that intentionally, as I wanted to outline and underline basic concept to any beginner in this area.

Leave a Reply