Ajax: Creating Native JavaScript Objects From SQL - The Ajax client page
(Page 4 of 4 )
Now that we've seen how the backend works, we are ready to investigate the JavaScript side of things. This is where the benefits of using JSON as a data format become very obvious.
ajaxtest.html is just an HTML file with JavaScript. All the logic on the page runs entirely on the client side, in the browser of the user. If you have successfully modified and gotten response.aspx to query against your Northwind database in the sample, you can load ajaxtest.html in your browser and see how it works.
Figure 3
On load, ajaxtest.html queries the "categories" table in the Northwind database, and populates a select list with the categories. Upon selection of one of these categories, it outputs the products of that category in a formatted table. It also uses a <div> to output the JSON directly for debugging.
The body of ajaxtest.html is as follows.
<body onload="loadCats()">
<form id="theForm">
<select name="selcats" onchange="outputProducts(this.value)">
</select>
</form>
<div id="formattedOutput">
</div>
<strong>Debug:</strong>
<div style="border:1px solid" id="debugOutput">
<div>
</body>
The form "theForm" contains a simple, empty select list called "selcats." This is automatically populated by the JavaScript function "loadCats()," which is executed when the page loads. This executes because of the onload="loadCats()" part of the <body> tag.
// Load categories from Northwind databases
// (This occurs on page load)
function loadCats()
{
http.open('get','response.aspx?sql=select CategoryID,
CategoryName from categories&rand=' + genSeconds() );
http.onreadystatechange = loadCatsCallback; // (See following
function)
http.send(null);
return false;
}
loadCats() uses an XMLHttpRequest object, http, which is created by the function createRequestObject() when the page is first loaded into the browser. createRequestObject() creates the appropriate XMLHttpRequest object for the browser being used (IE and Mozilla have different requirements) and returns it. Once http has been created, it can be used to send requests to response.aspx.
Above, I use http.open to call response.aspx with the SQL command asking for the CategoryID and CategoryName from the Northwind "categories" table. I assign the function loadCatsCallback() as the callback handler. When response.aspx returns the JSON data, this function will do something with it. Specifically, it will output it as <option> tags in "selcats."
function loadCatsCallback()
{
if(http.readyState == 4)
{
// Create object from JSON notation. Note
// use of 'eval'
var jsonObject = eval(http.responseText);
// Check that there wasn't an error
if (jsonObject.error == null)
{
document.forms['theForm'].selcats.options[0] =
new Option('', ''); // The empty option
// Loop through records, build <select> list
for (var i=0; i < jsonObject.totalRows; i++)
{
document.forms['theForm'].selcats.options[i+1] =
new Option( jsonObject.rows[i].CategoryName,
jsonObject.rows[i].CategoryID );
}
}
else
alert("Error occurred: " + jsonObject.error);
// Send information to debug <div>
document.getElementById('debugOutput').innerHTML =
"loadCatsCallback() JSON: " + http.responseText;
}
} // loadCatsCallback()
In loadCatsCallback() above, I first check that the data has returned via readyState. Once it has, I create a variable called jsonObject using eval(). This is all there is to turning the data gotten from response.aspx into a usable JavaScript object. Convenient, yes? Now, I check the "error" member to see if it is null. If it is, then no errors have occurred, and we can process the object.
It's a simple matter to iterate through the jsonObject.rows array -- I create a for loop that counts from zero up to the value stored in jsonObject.totalRows, and obtain the values for the columns in each row by referring to their names. Notice that the value for the SQL column "CategoryID" is gotten by jsonObject.rows[i].CategoryID -- as a variable. For each element in jsonObject.rows, I add a new Option to "selcats." I also output the straight JSON data to "debugOutput," using the innerHTML property of that <div> element.
Now, when you select a value in the "selcats" list, the function outputProducts() fires, passing the CategoryID of the selected option as a parameter. The ensuing code calls response.aspx with a SQL query to return products for that CategoryID, constructs a table from the query, and inserts it into the "formattedOutput" <div> using the innerHTML property. This code behaves in essentially the same way as that outlined above, so I will not cover it here.
Conclusion
JSON allows you to easily get at data in a native way with JavaScript, reducing the amount of code needed to process datasets. It executes fast, it's easy to work with, and very convenient. It may not be the answer for every Ajax situation, but it's certainly an important and powerful tool in the Ajax toolset.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |