23
Sat, Nov
1 New Articles

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.

Jeff Olen

Jeff Olen is a super-spy now but keeps his cover identity intact by working for video game studios on the East Coast. So when he’s not out killing members of ISIS or rescuing refugees, you can find him playing Wolfenstein II or testing the new Fallout 76 releases at his beach house in Costa Rica. In any case, he can’t be reached. You can email his cat at This email address is being protected from spambots. You need JavaScript enabled to view it.. She will pass on your message…if she feels like it.


MC Press books written by Jeff Olen available now on the MC Press Bookstore.

The IBM i Programmer’s Guide to PHP The IBM i Programmer’s Guide to PHP
Get the scoop on how PHP can—and should—be deployed on IBM systems.
List Price $79.95

Now On Sale

BLOG COMMENTS POWERED BY DISQUS

LATEST COMMENTS

Support MC Press Online

$

Book Reviews

Resource Center

  • SB Profound WC 5536 Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application. You can find Part 1 here. In Part 2 of our free Node.js Webinar Series, Brian May teaches you the different tooling options available for writing code, debugging, and using Git for version control. Brian will briefly discuss the different tools available, and demonstrate his preferred setup for Node development on IBM i or any platform. Attend this webinar to learn:

  • SB Profound WP 5539More than ever, there is a demand for IT to deliver innovation. Your IBM i has been an essential part of your business operations for years. However, your organization may struggle to maintain the current system and implement new projects. The thousands of customers we've worked with and surveyed state that expectations regarding the digital footprint and vision of the company are not aligned with the current IT environment.

  • SB HelpSystems ROBOT Generic IBM announced the E1080 servers using the latest Power10 processor in September 2021. The most powerful processor from IBM to date, Power10 is designed to handle the demands of doing business in today’s high-tech atmosphere, including running cloud applications, supporting big data, and managing AI workloads. But what does Power10 mean for your data center? In this recorded webinar, IBMers Dan Sundt and Dylan Boday join IBM Power Champion Tom Huntington for a discussion on why Power10 technology is the right strategic investment if you run IBM i, AIX, or Linux. In this action-packed hour, Tom will share trends from the IBM i and AIX user communities while Dan and Dylan dive into the tech specs for key hardware, including:

  • Magic MarkTRY the one package that solves all your document design and printing challenges on all your platforms. Produce bar code labels, electronic forms, ad hoc reports, and RFID tags – without programming! MarkMagic is the only document design and print solution that combines report writing, WYSIWYG label and forms design, and conditional printing in one integrated product. Make sure your data survives when catastrophe hits. Request your trial now!  Request Now.

  • SB HelpSystems ROBOT GenericForms of ransomware has been around for over 30 years, and with more and more organizations suffering attacks each year, it continues to endure. What has made ransomware such a durable threat and what is the best way to combat it? In order to prevent ransomware, organizations must first understand how it works.

  • SB HelpSystems ROBOT GenericIT security is a top priority for businesses around the world, but most IBM i pros don’t know where to begin—and most cybersecurity experts don’t know IBM i. In this session, Robin Tatam explores the business impact of lax IBM i security, the top vulnerabilities putting IBM i at risk, and the steps you can take to protect your organization. If you’re looking to avoid unexpected downtime or corrupted data, you don’t want to miss this session.

  • SB HelpSystems ROBOT GenericCan you trust all of your users all of the time? A typical end user receives 16 malicious emails each month, but only 17 percent of these phishing campaigns are reported to IT. Once an attack is underway, most organizations won’t discover the breach until six months later. A staggering amount of damage can occur in that time. Despite these risks, 93 percent of organizations are leaving their IBM i systems vulnerable to cybercrime. In this on-demand webinar, IBM i security experts Robin Tatam and Sandi Moore will reveal:

  • FORTRA Disaster protection is vital to every business. Yet, it often consists of patched together procedures that are prone to error. From automatic backups to data encryption to media management, Robot automates the routine (yet often complex) tasks of iSeries backup and recovery, saving you time and money and making the process safer and more reliable. Automate your backups with the Robot Backup and Recovery Solution. Key features include:

  • FORTRAManaging messages on your IBM i can be more than a full-time job if you have to do it manually. Messages need a response and resources must be monitored—often over multiple systems and across platforms. How can you be sure you won’t miss important system events? Automate your message center with the Robot Message Management Solution. Key features include:

  • FORTRAThe thought of printing, distributing, and storing iSeries reports manually may reduce you to tears. Paper and labor costs associated with report generation can spiral out of control. Mountains of paper threaten to swamp your files. Robot automates report bursting, distribution, bundling, and archiving, and offers secure, selective online report viewing. Manage your reports with the Robot Report Management Solution. Key features include:

  • FORTRAFor over 30 years, Robot has been a leader in systems management for IBM i. With batch job creation and scheduling at its core, the Robot Job Scheduling Solution reduces the opportunity for human error and helps you maintain service levels, automating even the biggest, most complex runbooks. Manage your job schedule with the Robot Job Scheduling Solution. Key features include:

  • LANSA Business users want new applications now. Market and regulatory pressures require faster application updates and delivery into production. Your IBM i developers may be approaching retirement, and you see no sure way to fill their positions with experienced developers. In addition, you may be caught between maintaining your existing applications and the uncertainty of moving to something new.

  • LANSAWhen it comes to creating your business applications, there are hundreds of coding platforms and programming languages to choose from. These options range from very complex traditional programming languages to Low-Code platforms where sometimes no traditional coding experience is needed. Download our whitepaper, The Power of Writing Code in a Low-Code Solution, and:

  • LANSASupply Chain is becoming increasingly complex and unpredictable. From raw materials for manufacturing to food supply chains, the journey from source to production to delivery to consumers is marred with inefficiencies, manual processes, shortages, recalls, counterfeits, and scandals. In this webinar, we discuss how:

  • The MC Resource Centers bring you the widest selection of white papers, trial software, and on-demand webcasts for you to choose from. >> Review the list of White Papers, Trial Software or On-Demand Webcast at the MC Press Resource Center. >> Add the items to yru Cart and complet he checkout process and submit

  • Profound Logic Have you been wondering about Node.js? Our free Node.js Webinar Series takes you from total beginner to creating a fully-functional IBM i Node.js business application.

  • SB Profound WC 5536Join us for this hour-long webcast that will explore:

  • Fortra IT managers hoping to find new IBM i talent are discovering that the pool of experienced RPG programmers and operators or administrators with intimate knowledge of the operating system and the applications that run on it is small. This begs the question: How will you manage the platform that supports such a big part of your business? This guide offers strategies and software suggestions to help you plan IT staffing and resources and smooth the transition after your AS/400 talent retires. Read on to learn: