Using DOM Scripting to Parse AJAX Responses with JavaScript - Using DOM scripting to parse plain text responses with AJAX
(Page 3 of 4 )
As I mentioned in the section that you just read, I'm going to define a brand new JavaScript function for parsing all of the user data fetched from the corresponding "Users" database table that I showed you earlier.
This function, which I called "displayResults()" has the following signature:
function displayResults(userData){
var datacont=document.getElementById('datacontainer');
if(!datacont){return};
var userData=userData.split('|');
if(userData.length>0){
var cont=document.getElementById('container');
if(cont){cont.parentNode.removeChild(cont)};
var div=document.createElement('div');
div.setAttribute('id','container');
for(var i=0;i<userData.length;i++){
var h3=document.createElement('h3');
var par=document.createElement('p');
h3.appendChild(document.createTextNode(userData[i].split(':')
[0]));
par.appendChild(document.createTextNode(userData[i].split(':')
[1]));
div.appendChild(h3);
div.appendChild(par);
}
datacont.appendChild(div);
}
setTimeout("sendHttpRequest
('get_user_data.php','displayResults')",5*1000);
}
As you can see, the above "displayResult()" JavaScript function behaves nearly the same as the one created in the previous article of the series. However, despite this similarity, it parses all of the user data by using some common DOM methods. In this case, once the correct database row has been fetched from the "Users" database table, its different fields are split up by using a simple "|" delimiter before sending it back to the browser.
On the client side, the prior "displayResults()" function expects the data to come in that concrete format. It uses the DOM to display this data using some <h3> headers and a few paragraphs, which are dynamically appended to the wed document tree.
Finally, the function fetches cyclically from MySQL the different database rows every five seconds, by utilizing a conventional JavaScript timer.
Do you see how easy it is to parse server-side data sent in plain text using some DOM scripting, from inside the context of an AJAX application? I hope you do! This approach requires writing a few additional lines of code, but it uses fully standard DOM methods.
So far, so good. At this stage I demonstrated how to utilize a completely standard approach to parsing data coming from the web server, based upon an AJAX-based HTTP request. Nonetheless, this sample AJAX application looks rather disjointed, since I showed you each of its pieces separately.
Therefore, in the last section of this tutorial I'm going to list the complete source code of the AJAX application, so you can see more clearly how its different modules link with each other.
As I said before, this will be done in the next few lines, thus click on the link below and keep reading.
Next: Listing the complete source code >>
More JavaScript Articles
More By Alejandro Gervasio