Get Moving with Mobile Apps Using Cordova, Part 3

Development Tools / Utilities
Typography
  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

Finally, add a database backend to your mobile app.

 

In parts 1 and 2 of this series, we built a simple to-do list application. Now we come to the final step in the process: adding the backend database. Previously, in part 2, we could add and delete the to-do list items in the Document Object Model (DOM), but they weren't saved anywhere and therefore would not persist between instances of the application.

 

The first thing I should explain is that in this article we're going to cover only the code for the AJAX interface in the mobile application. The actual backend server/service you create can be any number of types of application (PHP, Ruby on Rails, Node.js, etc.), and there are many examples and tutorials available for learning to build them. That said, here's a link to the Ruby on Rails github repository for the service that I built for this article. And here's a link to the Cordova app.  

 

So without further adieu…

 

HTML Changes

One of the nice things about the UI we've built is that it's easily modified to work with a persisted data source. Only one line of code needs to be changed in the HTML. We're just going to remove our placeholder. If we want or need a placeholder, then we can deal with that from the server side. So the code will look as shown below:

 

       <div data-role="content">

           <ul id="item-list" data-role="listview" data-icon="delete">

           </ul>

         </div>

 

JQuery and JavaScript Changes

As you may have expected, most of our changes are going to be in the JavaScript. The first thing we're going to do is remove the code that was used to remove the placeholder item. So the addListItem function will be as shown below:

 

   addListItem: function() {

     if ($("#item").val() != "") {

         new_item = $("<li><a href='#' class='ui-btn ui-btn-icon-right ui-icon-delete'>"+$("#item").val()+"</a></li>");

         $(new_item).click( function(e) {

           e.target.remove();

         });

         $("#item-list").append(new_item)

       $("#item").val("")

       window.location.href = "#mainpage"

   }

   },

 

We 're going to need several AJAX operations to make our application function correctly. We'll need 1) a function to retrieve all the existing rows, 2) a function to add a new row, and 3) a function to delete an existing row. We'll start with the function to retrieve all existing rows. Add the following code below the addListItem function:

 

   fetchItemsList: function() {

     items = [];

     $.ajax({

       type: "GET",

       url: "http://localhost:3000/items.json",

       success: function(data) {

         for( var i=0; i < data.length; i++) {

           app.insertNewItem(data[i].description, data[i].id);

         };

       }

     });

     return items;

   },

 

The code above is using the JQuery .ajax method to simplify the AJAX call to the server. JQuery documentation can be found at JQuery.com. The gist of what is happening in this code is that we're making a GET request to the server at http://localhost:3000 for items.json. The localhost server is just my laptop, and 3000 is the port I have my Ruby on Rails server listening on. If the request completes successfully, then whatever is returned from the server will be placed in the "data" parameter passed to the function we define for "success:".

 

So what happens on the server side, one may ask? Well, in the case of the backend I'm using, the server retrieves the rows from my "todo" database and returns them as JSON objects. If you want to see this, you can load the backend server and get it running on your laptop. Then put the URL from the .ajax method into your browser. You should get something that looks like this:

 

[{"id":28,"description":"Grocery shopping","created_at":"2015-09-17T20:08:56.944Z","updated_at":"2015-09-17T20:08:56.944Z"},{"id":29,"description":"Feed cat","created_at":"2015-09-17T20:08:56.955Z","updated_at":"2015-09-17T20:08:56.955Z"},{"id":30,"description":"Clean house","created_at":"2015-09-17T20:08:56.968Z","updated_at":"2015-09-17T20:08:56.968Z"},{"id":31,"description":"Wash the car","created_at":"2015-09-17T20:08:56.975Z","updated_at":"2015-09-17T20:08:56.975Z"},{"id":32,"description":"Write Cordova article","created_at":"2015-09-17T20:08:56.977Z","updated_at":"2015-09-17T20:08:56.977Z"},{"id":33,"description":"Do dishes","created_at":"2015-09-17T20:08:56.978Z","updated_at":"2015-09-17T20:08:56.978Z"}]

 

This is just the JSON for the rows I loaded for testing purposes. So that's what the "data" parameter will contain. You may have noticed that the function that gets called when the AJAX request completes successfully is calling another function that we haven't written yet: app.insertNewItem.

 

The reason I did this is that we're going to need to be able to add a new item to our display both when we load the complete list and also when we add a new item to it from the add display. So it's best to separate that processing. Here's the code for the insertNewItem function. It should be added above the fetchItemsList function.

 

     insertNewItem: function(description, id) {

       if (id == undefined) {

         $.ajax({

           type: "POST",

           url: "http://localhost:3000/items.json",

           data: { description: description },

           success: function(data) {

             id = data;

             $("#item-list").find("#undefined").attr("id",id)

           },

           fail: function() {

             alert("add failed!")

           }

         });

       }

       new_item = $("<li id='"+id+"'><a href='#mainpage' class='ui-btn ui-btn-icon-right ui-icon-delete'>"+description+"</a></li>");

     new_item.click( function(e) {

        if (e.target.parentElement.id != 0 && e.target.parentElement.id != "undefined") {

         app.deleteItem(e.target.parentElement.id)

       }

       e.target.remove();

     });

     $("#item-list").append(new_item)

   },

This function also makes an AJAX request, but in this case it will do that only if the "id" passed to the function is equal to "undefined." That code will make more sense in a moment. In this case, we're making a POST request to the same URL as we used before in the fetchItemsList. This is a Ruby on Rails convention for routing and will trigger the "create" method on the backend server. A new row will be created in the database using the data from the object specified on the "data:" parameter of our $.ajax method. Again the data being passed to and from the server is JSON, so here we're creating a JSON object on the fly that just contains the description of our to-do item. Upon successful return from the server, we will receive the "id" of the added row.

 

Here's where things get a bit confusing if you're unfamiliar with the asynchronous nature of AJAX. When the server request is made, we know the "id" passed to the function is "undefined" because we're checking that on the way in. So the AJAX request is made to the server, but the JavaScript doesn't wait for a response. It simply keeps going. Therefore, a new item with an "id" equal to "undefined" is added to the DOM in the code following the AJAX request. This is our newly added to-do item. When the server request completes, then we'll have the actual "id" of the added database row. At that point, we want to change the "id" of the item in the DOM to match the actual row id. We'll need that later when we add the delete function. This line from the "success:" function takes care of that for us.

 

     $("#item-list").find("#undefined").attr("id",id)

 

There are some potential for issues with this handling in a production environment, but for demo purposes it's enough.

The only other thing worth mentioning in this code is the event listener we add to the new line item. We're using JQuery to set a listener that will trigger the function we specify (app.deleteItem, which we still need to write) when the user clicks on the line item. The rest of the JavaScript in the insertNewItem function should be clear enough if you worked through the first two articles.

 

The last part of the add process will be to change the current addListItem function to use our new insertNewItem function. So the new addListItem function is as shown below:

 

   addListItem: function() {

     if ($("#item").val() != "") {

       this.insertNewItem($("#item").val());

       $("#item").val("")

       window.location.href = "#mainpage"

     }

   },

 

Notice that in the case of a newly added item we're only passing the description we entered, not passing a parameter for the "id" at all. Thus the "id" will be "undefined" inside the insertNewItem function and it will make the AJAX request as it should.

 

So now we can fetch the list and add to it. Let's wrap up with the delete function. This is simple enough. We already added the event listener that will trigger the delete function called app.deleteItem. Add the following code after the fetchItemList function.

 

   deleteItem: function(id) {

     url = "http://localhost:3000/items/"+id+".json"

     $.ajax({

       type: "POST",

       url: url,

       fail: function() {

         alert("delete failed!")

       }

     });

   }

 

After you've coded the other two AJAX requests, this one should appear pretty simple. We set the URL using the "id" passed to the function. Make the POST request and check and report if it fails.

 

One last thing: we need to add the initial (only) call to the fetchItemList function when the app first loads. So change the code in the bindEvents function as shown below.

 

   bindEvents: function() {

       document.addEventListener('deviceready', this.onDeviceReady, false);

       this.fetchItemsList();

   },

 

That's it. You now have a fully functioning mobile app. Well, unless you have syntax errors in your code. Since debugging a mobile app can be challenging, let me offer a few tips. If you remove the JQuery mobile UI library and the "viewport" meta-name tag, you can load the index.html in your browser and test it there. If you're using Google Chrome, check out the Developer Tools displays as they are enormously helpful in debugging your JavaScript. Also, liberal use of the JavaScript alert command can be helpful from within the app itself. Just remember to remove them all once you're done debugging.

BLOG COMMENTS POWERED BY DISQUS