Nitobi
Customer Login
Services
Products
About
Blogs
Contact
Home -> Product Knowledgebase Order Online | Free Trial Downloads

Nitobi Product Knowledgebase

Ajax Databinding Tutorial


There are two ways to bind Grid to data. One is to static data contained on the page, and the other is to use Ajax to call back to the server for it. Nitobi Grid uses XMLHttp to load and save data to remote datasources. An API is provided to format data according to the Nitobi XML schema in a variety of platforms including Java, PHP, Classic ASP, and Coldfusion.

Parts of a Databound Grid

There are several key components to a databound grid. Each of these is represented by an actual page sitting on the server which is called by the Grid at runtime.

  • getHandler - Loads data from the database and converts it to XML for the grid
  • saveHandler - Takes updategrams from the grid and converts them to UPDATE's, INSERT's, and DELETE's for the database. This is an optional feature.
  • keyGenerator - Tells the grid what primary keys to use for newly inserted records. Without this, the grid will assign its own random keys to new rows, which need to be put into the database. The keygenerator is only needed if you are allowing users to insert new rows into the database.

Writing a getHandler

Gethandlers provide data to the Grid and to editors like Lookups and Listboxes. The first step now is to write a gethandler which is in this case an ASP script that outputs XML. Grid calls this page using XMLHttp and displays the data in the grid. The first step is to define it in the grid tag.

 <ntb:grid id="DataboundGrid"  
  <!-- other attributes removed for brevity -->
  gethandler="load_data.asp"> 

Then, we create an Java, PHP, or ASP document that listens for several querystring parameters that tell us where to start returning data:

  • StartRecordIndex - Which record (ordinally) to start returning data on.
  • PageSize - How many records to return
  • SortColumn - Which is the currently sorted column (could be blank)
  • SortDirection - (Asc or Desc) The direction of sorting
  • TableId - The datatable being used (by default is _default)

For information on writing getHandlers, choose your platform:

How do we debug our gethandler? Try calling your page with test parameters like this:

load_data.asp?StartRecordIndex=10&PageSize=20&SortColumn=&SortDirection=&TableId=_default

.. and go View-source. Make sure you see nicely formatted XML. Alternatively, you can use a tool like FireBug for Firefox to watch the actual XMLHttp requests and view the response (if you aren't getting data in the grid).

Writing a saveHandler

The Savehandler accepts Ajax form posts with XML as the form contents and converts those into SQL instructions to update the datatable. First, we define our savehandler in the Grid tag.

 <ntb:grid id="DataboundGrid"  
  <!-- other attributes removed for brevity -->
  gethandler="load_data.asp"
  savehandler="save_data.asp"> 

Then we use the Nitobi XML API to assist converting this xml updategram to SQL statements.

For information on writing saveHandlers, choose your platform:

Writing a keyGenerator

Just like a database table, every record needs a primary key. When inserting new records into a grid we instantly have a small problem in that the Grid needs to assign a primary key to that record in order to keep track of it and synchronize with the database. For this purpose Grid supports a KeyGenerator.

A KeyGenerator is a JavaScript function that executes when you save and must return a primary key for each row. Grid will take this key and assign it to the record and use it to refer to that record from now on. Note: if you do not specify a keygenerator, grid will assign a random key to that record.

There are may ways to tackle this problem, but one way that reduces the amount of legwork on the server is to actually insert the record to the database in the KeyGenerator, not the savehandler and return its primary key. Then, in the savehandler, simply update your already inserted record instead of inserting it.

 <ntb:grid id="DataboundGrid"
   
  keygenerator="GetNewRecordID()"
  autosaveenabled="true"
  
  gethandler="load_data.asp"
  savehandler="save_data.asp">

GetNewRecordID()


 <script>  
function GetNewRecordID()
{
  // Use the native cross-browser nitobi Ajax object
  var myAjaxRequest = new nitobi.ajax.HttpRequest();
  
  // Define the url for your generatekey script
  myAjaxRequest.handler = 'allocaterecord.jsp?rnd=' + Math.random();
  myAjaxRequest.async = false;
  myAjaxRequest.get();
  
  myResultKey = myAjaxRequest.httpObj.responseText;
  myResultKey.replace(/s/g, '');
  myResultKey = parseInt(myResultKey) + 1;
  
  // return the result to the grid
  return myResultKey.toString();
}
 </script>

Then you need to write a servelet, php script, or asp script to return a number that can be used as the primary key for the record. This number will be returned from GetNewRecord() and put into the Grid data.

Classic ASP Version

 <%@ Language=VBScript %>
 
 <%
 
 ' Set up database connection here
 
 
 dim MyQuery
 dim uid
 dim myNewRecordID
 
 ' Using the current date and time gives us a unique string to search for
 uid = cstr(now())
 
 
 MyQuery = "INSERT INTO tblContacts3k (ContactName) VALUES ('" & uid & "');"
 ' Now we execute this query
 objConn.execute(MyQuery)
 
 MyQuery = "SELECT ContactID, ContactName FROM tblContacts3k"_
   & "WHERE ContactName LIKE '" & uid & "'"
 
 dim RecordSet
 Set RecordSet = objConn.execute(MyQuery)
 
 do while not RecordSet.eof
 
  myNewRecordID = RecordSet("ContactID")
  RecordSet.MoveNext
 loop
 
 RecordSet.close
 
 objConn.close
 
 ' Now we output the number
 
 Response.Write(myNewRecordID)
 
 %>

JSP Version

 String randomNumber=request.getParameter("rnd");
 if (randomNumber==null)
  {
   randomNumber="123456789";
  }

 String pathAfterContext = request.getServletPath();
 // remove the get.jsp part.
 pathAfterContext = pathAfterContext.substring(0,pathAfterContext.lastIndexOf("')).replace('/','');

// get the complete path on the server of our database.
 String path = config.getServletContext().getRealPath("') + pathAfterContext + "dataGeneralProducts.mdb";
 
 // get the database connection
 Class.forName("sun.jdbc.odbc.JdbcOdbcDriver").newInstance();
 Connection con=DriverManager.getConnection("jdbc:odbc:Driver={MicroSoft Access Driver (*.mdb)};DBQ=" + path,"","");

 Statement st=con.createStatement();
 
 String newQuery = "INSERT INTO tblproducts (ProductName) VALUES ('" +
  randomNumber + "')";

 st.executeUpdate(newQuery);
 
 newQuery = "SELECT ProductID FROM tblproducts WHERE ProductName LIKE '" +
  randomNumber + "';";
 
 ResultSet rs = st.executeQuery(newQuery);
 
 String ProductID = "none";
 
 while ( rs.next() )
 {    
   ProductID = rs.getString("ProductID");
 } 
 
 newQuery = "UPDATE tblproducts SET ProductName = '' WHERE ProductID LIKE " +
  ProductID;

 st.executeUpdate(newQuery); 

 st.close();

 // clean up
 out.println(ProductID);
 con.close();

PHP Version

 <?
 
 // Make a MySQL Connection
 mysql_connect("localhost", "root", "mypassword") or die(mysql_error());
 mysql_select_db("nitobi_testdb_V1") or die(mysql_error());
 
 $myRandomVar = time();
 
 $myQuery = "INSERT INTO tblproducts (ProductName) VALUES ('".$myRandomVar ."')";
 mysql_query($myQuery);
 
 $myQuery = "SELECT * FROM tblproducts WHERE ProductName LIKE '".$myRandomVar."';";
 $result = mysql_query($myQuery);
 
 $row = mysql_fetch_array($result);
 $myID = $row["ProductID"];
 
 $myQuery = "UPDATE tblproducts Set ProductName = '' WHERE ProductID = ".$myID;
 mysql_query($myQuery);
 
 mysql_close();
 
 echo $myID;
 ?>

Related Articles

View Printable Version

Comments:


Name:

Type the text you see above:

Comments:


Knowledgebase

To be notified of new articles when they're available, subscribe to our RSS feed.

Support Resources

Take advantage of our knowledgebase of product tutorials and tips, and our support forums!

Search Site


Sign up for our Newsletter:

Get industry articles and Nitobi company news in your inbox every couple of months — here's a sample!

Email:




Site RSS Feed  | All contents are (c) Copyright 2006, Nitobi Software Inc. All rights Reserved