Loading external data into a PhoneGap app using the jQuery JSONP plugin for cross-domain access
Important: view updated article – 9th July 2011
Following the release of jQuery 1.5 I have written a more up to date article and made available all of the source code and sample app.
Continuing my love affair with PhoneGap I thought I’d share a few methods of handling external data that I’ve adopted, tweaked and re-written for use in my web app escapades at RITH.
PhoneGap doesn’t ship with a data layer but as web apps [commonly] utilise a JavaScript library, this isn’t an issue. I use jQuery, but it is worth noting there are several other more compact JS libraries that may be more suitable if you want to keep your app as lightweight as possible.
This isn’t solely related to PhoneGap apps – this technique can be used in any web app, but it’s immensely useful within PhoneGap.
Introducing jQuery.ajax()
jQuery.ajax() is the foundation for all data loading requests when using jQuery, and according to their API reference; allows us to Perform an asynchronous HTTP (Ajax) request. Splendid.
The request is very simple in essence:
$.ajax({
url: 'your-url',
success: function(data) {
//it works, do something with the data
},
error: function() {
//something went wrong, handle the error and display a message
}
});
Selecting a suitable data source
This ajax request can pull all sorts of data into your app but my experience has mainly been with JSON. I like to think of JSON as a designers XML – well formed JSON is beautiful and really easy to read and understand.
Unfortunately jQuery.ajax only works with content on the same domain. Cross-domain content requires you using jQuery.getJSON (JSONP). But rather annoyingly getJSON only allows for a success handler and not an error handler or timeout value, making it quite useless if you want to give you users a heads up on any data connection/response issues.
Fortunately there is a super-lightweight JSONP jQuery plugin (I hate using plugins in general, but this is an exception), and it’s marvelous.
Using the JSONP jQuery plugin
Within a recent app I was pulling in JSON from a University library, a live feed of transactions from thousands of users. These particular feeds aren’t public but the same principle can be applied to any source, so I’ll use my Twitter feed as an example from here onwards.
The HTML foundation
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Loading data into a PhoneGap app</title> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <script src="jquery.jsonp-2.1.4.min.js"></script> </head> <body> <ul id="your-tweets"></ul> </body> </html>
All I have here is some basic HTML markup, the latest version of jQuery and the JSONP plugin and an unordered list that will contain the output of a simple data request.
Loading the JSON object
Just as with jQuery.ajax, the JSONP request is very simple to set up.
<script>
$(document).ready(function(){
$.jsonp({
url: 'http://twitter.com/status/user_timeline/samcroft.json?count=20',
callbackParameter: 'callback',
success: function(data, status) {
//$('#your-tweets').append('<li>The feed loads fine');
$.each(data, function(i,item){
var tweet = item.text;
$('#your-tweets').append('<li>'+tweet);
});
},
error: function(){
$('#your-tweets').append('<li>There was an error loading the feed');
}
});
});
</script>
Code explanation
Line 4 is a reference the url for the JSON feed.
Line 5 is very important; this specifies the callback parameter for the cross-domain access. This must be as specified in the API you are working with or within your own server side code that is outputting JSON.
Line 6 is the success handler, code within this function will run if the feed reference in line 2 was successfully loaded. Here the contents of the JSON object is stored in the variable data.
Line 7 is commented out, but I like to print out a success message, or simple alert(), to ensure the feed is loading.
Line 8 – 9 involves stepping through each item (my last 20 tweets) within the variable data and setting a couple of new variables. Twitter creates it’s JSON feeds as an array of account tweets, so firstly the variable i refers to the current number of object within the array, so 0-19 in this case. The second variable ‘item’ is how I access string values within each object.
Here I am just loading the text string which is the text content of each tweet. But I could change this, or include others, like the created_at string, which is a date-time stamp for each tweet. To do this I would simply add;
var date = item.created_at;
Line 10 is where I take the values from each tweet and append it to my unordered list.
Line 13-15 is a little error handler that displays a message if there is a problem loading the JSON. This, however, only triggers if there is a direct problem in accessing the feed.
To communicate a slow response time it’s always good to include a timeout parameter. Breaching the specified timeout value (in milliseconds) will run code within the error handler. To do this I can amend my JSONP setup to timeout after 25 seconds. While I’m at it I can also indicate the tweets are loading when the page is loading;
<script>
$(document).ready(function(){
$('#your-tweets').append('<li>Loading Sam Croft\'s tweets');
$.jsonp({
url: 'http://twitter.com/status/user_timeline/samcroft.json?count=20',
callbackParameter: 'callback',
timeout: 25000,
success: function(data, status) {
//$('#your-tweets').append('<li>The feed loads fine');
$('#your-tweets').empty();
$.each(data, function(i,item){
var tweet = item.text;
$('#your-tweets').append('<li>'+tweet);
});
},
error: function(){
$('#your-tweets').append('<li>There was an error loading the feed');
}
});
});
</script>
View demo of this code loading my tweets into an HTML document using jQuery and JSONP.
Putting it all together in PhoneGap
Using the above method of loading JSON objects in a PhoneGap application is largely dependant on how you are developing your app and whether you are using any frameworks. But if you’re unfamiliar with PhoneGap, the process of utilising this method couldn’t be easier. You simply use this script within your HTML documents in your WWW folder and build your app.

Once you use this method it really opens up the possibilities of the kinds of application you can develop.
Important: view updated article – 9th July 2011
Following the release of jQuery 1.5 I have written a more up to date article and made available all of the source code and sample app.
Pingback: Updated: loading external data into an iOS PhoneGap app using jQuery 1.5
Pingback: Handige links - Webdevelopment blog | Webdevelopment blog