Posting data from a PhoneGap app to a server using jQuery
Recently I’ve had several requests to create an article about posting data to a server from a PhoneGap app so I thought I’d cover the steps I go through when dealing with this kind of requirement.
The method is extremely simple providing a few important steps are followed.
Important: Although not necessary, the context of this article will be better understood if you have read my previous article, Updated: loading external data into an iOS PhoneGap app using jQuery 1.5.
The reference to landmarks throughout this article refers to a barebones app I created in the aforementioned article where I was listing the geo-coordinates of several well known UK landmarks.
Creating an iOS PhoneGap app with Xcode 4
The first step is to create a new iOS PhoneGap app. Open the project location in finder, create your www folder and add it to the project in Xcode. You will also need the phonegap.js file if one isn’t already built when you compile. Make sure you use the corresponding version for your version of PhoneGap—I’m using phonegap-1.2.0.js.
Although I’m using iOS as the example, the project www files would be the same for Android and indeed any other supported platform.
Creating the form to post data from
Continuing with the example I created in my article about loading data from a server in a PhoneGap app, where I was loading geo coordinates for a few famous UK landmarks, I can expand on this and add a form for each landmark to submit data back to the server.
A simple comments form
I’m going to use a really simple form for each landmark so users can leave a comment about it.
<div id="landmark-1" data-landmark-id="1"> <form> <label for="email"> <b>Email</b> <input type="email" id="email" name="email"> </label> <label for="comment"> <b>Comment</b> <textarea id="comment" name="comment" cols="30" rows="10"></textarea> </label> <input type="submit" value="Save"> </form> </div>
I have used my preferred method of form markup.
Note: the intended use of this markup is that it is generated, or at least made visible, when a user taps an ‘add comment’ button. When this function is called the id for the landmark the user is commenting on is in the parent div as an id and custom data attribute. It could also be a hidden form field, but seeing as the id for the landmark is already available this seems unnecessary bloat.
How you go about integrating this is entirely based on your app and what fits best, I am merely mentioning what fits best with my landmarks app.
Using jQuery to handle and post form data
As with my previous articles I’m going to use jQuery for the JavaScript library but it’s worth mentioning that something like xui.js may be more suitable if you’re trying to create an app with as small a footprint as possible.
Using the .submit() event handler
While not necessary, it’s certainly considered correct to use jQuery’s .submit() event handler rather than an HTML button or link when dealing with forms.
A basic function assigned to the .submit() event handler:
$('form').submit(function(){
var landmarkID = $(this).parent().attr('data-landmark-id');
var postData = $(this).serialize();
$.ajax({
type: 'POST',
data: postData+'&lid='+landmarkID,
url: 'http://your-domain.com/comments/save.php',
success: function(data){
console.log(data);
alert('Your comment was successfully added');
},
error: function(){
console.log(data);
alert('There was an error adding your comment');
}
});
return false;
});
There are three important things going on in this function:
Line 2: firstly, I am grabbing the id for the landmark that is being commented on. I’m accessing this value from the custom data-landmark-id attribute in the parent div element.
Line 3: secondly, I am using jQuery’s serialize() method to gather all the data and values from the form. This is somewhat easier than stepping through each field and using the val() method. If I was to log the postData variable the output would be something like; email=me@site.com&comment=I like this location!
Lines 5-15: finally, I am using jQuery’s ajax() function to POST the data to a server. A successful POST will trigger one function while an error will trigger another.
This is the foundation for posting form data from a PhoneGap app.
Note: if you are creating your forms on-the-fly then you will need to use the live() event handler with your submit() event handler.
Using PHP to create a server-side component to store the data
My previous article about loading data from a server used PHP and MySQL so I’m going to continue with the same example and build on the database.
Creating a table to store the comments
First I’m going to create a small table that will contain all of the submitted comments.
CREATE TABLE `comments` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `location_id` int(11) DEFAULT NULL, `email` varchar(45) DEFAULT NULL, `comment` text, PRIMARY KEY (`id`) )
This is fairly self explanatory. I’m going to store the email address, comment and the location id.
Creating a tiny PHP script to handle and store the comments
The next part of submitting a comment is to create a PHP script that takes the data from the app, sanitises it and stores it in MySQL.
$server = "";
$username = "";
$password = "";
$database = "";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$locationID = $_POST["lid"];
$email = mysql_real_escape_string($_POST["email"]);
$comment = mysql_real_escape_string($_POST["comment"]);
$sql = "INSERT INTO comments (location_id, email, comment) ";
$sql .= "VALUES ($locationID, '$email', '$comment')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
Lines 1-4: set up database connection details.
Lines 6 & 8: connect with the MySQL server and select the database that will be used.
Lines 10-12: grab the POSTed form data from the PhoneGap app and sanatise any strings.
Lines 14-21: create a string with an SQL insert query and then execute the query. Return a success or error message.
Line 23: close the MySQL connection.
Testing the app in the iPhone simulator
The final step is to build and compile the app and see how it works in the iPhone simulator. Bear in mind a couple of things and a common oversight and you’ll be submitting data to your server with no problems.
Console logging is your friend
You’ll notice in the js function that I have a couple of console.logs that return the status of the comment save. These are great when you’re testing in your browser as you can see them in the developer console. And they also appear in the Xcode debug console (shift+cmd+c), so use them to step through your code if you are having issues.
Add your server to your app’s server whitelist
With PhoneGap 1.0 came the addition of server whitelists whereby you must declare any external hosts that you will be accessing data from or sending data to.
To add your server as an external host; view the PhoneGap.plist in Xcode (project navigator > project > supporting files) and add a new item within the ExternalHosts array for your server. In this example I’m using localhost so I’m going to go ahead and add a string value of localhost.
Because I’m using localhost I’m also going to add another string value – debug.phonegap.com. This explicitly states I am in debug mode, rather than release.
If I was using my own website as a data server I would add a string value of samcroft.co.uk and drop the debug.phonegap.com value.
This is just the basic outline
One final note is that this is just the basic outline in submitting data to a server from a PhoneGap app. Utilising this further you would have to consider how best to integrate with your app, create client and server side validation, have loading gifs, visually handle a complete form submission and maybe trigger a function that gathers the new data and appends it to any existing data already visible. I will cover all of this in another article if there is any interest.
Pingback: Updated: loading external data into an iOS PhoneGap app using jQuery 1.5
Pingback: I T | Pearltrees
Pingback: My article for Adobe’s Appliness magazine: Loading data into, and posting data from, a PhoneGap app
Pingback: Phonegap Tutorials « PHPsolutionBD