My 2010 post about loading data into a PhoneGap application is by far the most viewed page of my blog so I thought I’d revisit it and write an article about a more efficient method I have been using, following the release of jQuery 1.5.
Previously I had been using the wonderful JSONp jQuery plugin because jQuery 1.4 and lower did not support out of the box error handlers for JSON requests. jQuery 1.5 does, however, and it’s made things simpler and more streamlined.
LOADING DATA INTO PHONEGAP THE EASY WAY WITH JQUERY 1.5
With jQuery 1.5 it’s really simple to load external data into a PhoneGap app. The process is very similar to my previous method, just with a few subtle differences and of course; with the added benefit of not having to inclue a 3rd party plugin.
USING JQUERY.AJAX() FUNCTION TO CREATE A BASIC DATA REQUEST
This is such a powerful little function and, in my experience, is often the backbone of a PhoneGap app that relies on harnessing external data.
While this is an easy to understand function, there are a few important aspects that bring the whole thing together.
Lines 2 – while PhoneGap uses the file:// protocol and doesn’t have problems with cross-domain requests, I find that using the JSONp data type brings with it two wonderful benefits. Firstly, you can debug your app in a browser—a much simpler approach than using XCode’s console (if you’re working with iOS). And secondly, you have the added benefit of creating code that you can deploy in a browser based version of your app, circumventing any cross-domain issues.
Line 3 – when using the JSONp data type, one must provide a JSONp callback parameter. This is automatically appended to your URL and the value of which must be used within your server side code that outputs the data. This is what allows for the cross-domain request.
AN EXAMPLE OF HOW TO LOAD EXTERNAL DATA INTO A PHONEGAP APP
In my previous article I was loading a Twitter JSON feed into an app. This was fine at demonstrating the methods of bringing in that data to a PhoneGap app, but glossed over any server side functions that you would be required to create to setup the whole process.
What follows is a method that I have used to create server-side components that will output a JSON object being requested by a PhoneGap app. As an example I will run through the steps to create a fictional app that requests the names of and geo location coordinates of famous UK landmarks.
CREATING A SIMPLE MYSQL DATABASE TO HOLD DATA THAT THE PHONEGAP APP WILL REQUEST
The first step is create a database that will contain all of the information that the app may request. This article isn’t really about MySQL so I will run through this relatively quickly.
1
CREATETABLE'landmarks'(
2
'id'int(11) NOTNULLAUTO_INCREMENT,
3
'name'varchar(50) DEFAULTNULL,
4
'lat'decimal(18,12) DEFAULTNULL,
5
'long'decimal(18,12) DEFAULTNULL,
6
PRIMARYKEY('id')
7
)
Within this table I will add the names of some famous UK landmarks and their latitude and longitude values.
USING A BIT OF PHP TO HANDLE A DATA REQUEST FROM THE APP AND CREATE THE JSON OBJECT
With a few lines of PHP we can then query the landmarks table in the database and create the necessary JSON output, appending this to the aforementioned JSONp callback parameter.
1
<?php
2
header('Content-type: application/json');
3
4
$server= "localhost";
5
$username= "root";
6
$password= "";
7
$database= "landmarks";
8
9
$con= mysql_connect($server, $username, $password) ordie("Could not connect: ". mysql_error());
10
mysql_select_db($database, $con);
11
12
$sql= "SELECT id, l_name AS name, l_lat AS latitude, l_long AS longitude FROM landmarks ORDER BY l_name";
What the above snippet of PHP does is query the landmarks table and creates a JSON object with data from the result rows from the query. Note: on line 18 mysql_fetch_assoc is used to create a key=>value array before being converted to a JSON object on line 24.
The query in this example is very basic and is just intended to demonstrate the process. You must add your own MySQL connection details.
For reference; the JSON object returned would be an array in the following format:
1
[
2
{
3
"id": "1",
4
"name": "Big Ben",
5
"latitude": "51.500600000000",
6
"longitude": "-0.124610000000"
7
},
8
{
9
"id": "4",
10
"name": "Hadrian's Wall",
11
"latitude": "55.024453000000",
12
"longitude": "2.142310000000"
13
},
14
{
15
"id": "2",
16
"name": "Stonehenge",
17
"latitude": "51.178850000000",
18
"longitude": "-1.826446000000"
19
},
20
{
21
"id": "3",
22
"name": "White Cliffs of Dover",
23
"latitude": "51.132020000000",
24
"longitude": "1.334070000000"
25
}
26
]
USING JQUERY TO LOAD THE JSON OBJECT
Now that we have our PHP component creating a JSON object we can use some jQuery within our PhoneGap app to load the data.
1
$(document).ready(function(){
2
varoutput = $('#output');
3
4
$.ajax({
5
url: 'landmarks.php',
6
dataType: 'jsonp',
7
jsonp: 'jsoncallback',
8
timeout: 5000,
9
success: function(data, status){
10
$.each(data, function(i,item){
11
varlandmark = '<h1>'+item.name+'</h1>'
12
+ '<p>'+item.latitude+'<br>'
13
+ item.longitude+'</p>';
14
15
output.append(landmark);
16
});
17
},
18
error: function(){
19
output.text('There was an error loading the data.');
20
}
21
});
22
});
The important part in this snippet is lines 10 – 16. What happens here is that a function will iterate through each item in the JSON object array and retrieve the values using their key name. The results of which are then appended to an HTML element.
Running this application, you should see something like this:
Nice post, really.
Very helpful tutorial, thanks!