Forums >> Programming >> Open Source >>
The updateItem Application




Posted:
bvstone

The updateItem Application

 
The updateItem Application

Now that we have seen how we are displaying information from a file that can be updated, we now will focus on how the records are updated.

Not only does this application use node.js on the server side, but it also uses jQuery on the client side.  Following is the jQuery code used for updating and adding new records in our application:

var changedRRNs = [];

$(document).ready(function () {
	doBinds();
});

function doBinds() {
  fieldChange();
  updateRows();
}


function fieldChange() {
  $('body').on('change', ':input', function(event) {
    var changedRRN = $(this).closest('tr').attr('data-rrn');
    
    if ($.inArray(changedRRN, changedRRNs) < 0) {
      changedRRNs.push(changedRRN);
    }

  });    
  
}

function updateRows() {
  $('body').on('click', '.updateButton', function(event) {
    $.each(changedRRNs, function(index, rrn) {
      var thisRow = $('[data-rrn="' + rrn + '"');
      var formData = '';

      thisRow.removeClass('errorUpdating');
      thisRow.addClass('updating',1000);
    
      var i=0;
    
      $(':input', thisRow).each(function() {
        i++;
      
       if (i > 1) {
          formData = formData + '&';
       }
      
        formData = formData + encodeURIComponent($(this).attr('name')) + '=' + encodeURIComponent($(this).val());  
      });

      var postURI ='';
      var dataID = thisRow.attr('data-ID');

      if (dataID == 'detail') {
        postURI = '/updateItem/' + rrn;
      }
   
      if (postURI != '') {
    		$.post(postURI, formData, function( data ) {
  		  })
        .fail(function(errorThrown) {
           thisRow.addClass('errorUpdating',1000);
           console.log('error:' + errorThrown.responseText);  
         })    
    		.always(function() {
          thisRow.removeClass('updating',1000);
    		});
      }   

    }); 

    changedRRNs = []; 
    location.reload()
  });
}

At first this may seem like a lot, but when broken down into it's smaller units it becomes clear how things work.  Lets take high level look at the parts of this client side JavaScript:

  • changedRRNs - This is a global array used to keep track of the Relative Record Numbers that are changed.  
     
  • doBinds() - This is just a function I use to call all the binding functions when the page is loaded.  Instead of coding each of the jQuery action events this makes things cleaner and describes the actual actions that are used in the application.
     
  • fieldChange() - This jQuery action function is used to watch for changes to any input field on the page.  When a field changes we add the RRN to the changedRRN array for processing later.
     
  • updateRows() - this jQuery action function is triggered when the Update button is clicked.  When it is clicked we iterate through the list of changedRRNs.  We use the RRN to get the values from each of the fields in each row and call the jQuery .post() function (which is shorthand for an Ajax POST).

What's neat about the process is that we also update each row that is being updated with a class that makes it's background blue.  When the .post() is complete we remove the class to show the update is done.  If an error occurs during the update we add a class to the row to make it red to show that the row was NOT updated.  This type of DOM manipulation is what makes jQuery so powerful and easy to make your application appear more interactive.

The updateItem Node.js Application

In the above jQuery we see that the .post() function is made to /updateItem.  For each item that is updated we call this application to to update the specific record.

The server side updateItem.js application is as follows:

var express = require('express');
var myStuff = require('mymodules');
var router = express.Router();

var DBname = "*LOCAL";
var Library = 'BVSTONES';
var Table = 'ITEMPF';

router.post('/:rrn', function(req, res, next) {
  myStuff.setDBname(DBname);
  myStuff.setDBschema(Library);
  myStuff.setDBtable(Table);
  
  var rrn = req.params.rrn;
  
  if (rrn > 0) {
    var rc = myStuff.updateTableByRRN(rrn, req.body);
  } else {
    var rc = myStuff.insertIntoTable(req.body);
  }

  var result = 'Item Updated.'
  
  if (rc < 0) {
    result = 'Error updating item.';
  }
  
  res.send(result);
});

module.exports = router;

Again, we start with the requires.  In this case we are importing the standard functions for express as well as mymodules, which is the group of functions that I created specifically for data retrieval and updates on the IBM i.

We set the names of the database, library and table that we are working with.  In this case again it is the ITEMPF file in library BVSTONES.

In order to know which row to update we are passing in the Relative Record Number as a parameter on the call to the function:

  • /updateItem/<rrn>

The RRN in this case is used for the update because there's no way for each file to know the exact key fields to use for the update.  So as long as we aren't reorganizing our files every 10 minutes the RRN used in the web page should still match the RRN in the database itself and can be used for updating (or adding in this case).

Next we retrieve the parameters passed in when the .post() jQuery function made a POST request to our updateItem node.js application.  This will be a list of fields and their values.  If you recall when we created the list of items, each field had a name that was the actual database field name.  So, the past data would look something like this:

ITITEM=BLUECAR&ITIDESC=Light%20Blue%20Car&ITPRICE=1000.00&ITQTY=1

Now, the cool thing is when we request to use this data it's returned in JSON format so it's more usable in our application.  Here is what the data looks like using the req.body property:

{ ITITEM: 'BLUECAR',
  ITIDESC: 'Light Blue Car ',
  ITPRICE: '1000.00',
  ITQTY: '1' }

So, now that we have this we simply pass it into either the updateTableByRRN() or insertIntoTable() function.

In the next article we will finally take a look at the mymodules (mystuff) node.js module to see the nuts and bolts of the application and how we have started putting together our own set of functions to make database interaction easier.


Last edited 05/10/2016 at 10:34:58


Reply




Copyright 1983-2017 BVSTools
GreenBoard(v3) Powered by the eRPG SDK, MAILTOOL Plus!, GreenTools for Google Apps, jQuery, jQuery UI, BlockUI, CKEditor and running on the IBM i (AKA AS/400, iSeries, System i).