PHP and JavaScript Interaction: Storing Data in the Client, part 3 - Showing database records: the "displayRecords()" function (
Page 4 of 7 )
When it comes to displaying database records, we need to define a specific function to perform that task. Before we list the function code, let's explain how it will behave. Doing so, its logic will be much easier to understand. Take my word for it.
Since the records are already stored in the "rows" JavaScript array, the only assignment for this function is to extract the corresponding elements from it, and then insert their values into paragraph elements. Next, the whole set will be wrapped up by a regular <div> container and appended to the document tree. It's that simple.
I know that explaining this in words without showing any code is pretty pointless, so here's the listing for our "displayRecords()" function:
displayRecords=function(page){
var recsDiv=document.getElementById('records');
if(!recsDiv){return;}
var div=document.createElement('div');
div.id='records';
if(!page){page=1;}
// extract records from rows array
for(var i=(page-1)*recsPage;i<((page-1)*recsPage)+recsPage;i++){
if(rows[i]){
// insert records as paragraph elements
var p=document.createElement('p');
p.appendChild(document.createTextNode(rows[i]));
div.appendChild(p);
}
}
// replace old records node with new records node
recsDiv.parentNode.replaceChild(div,recsDiv);
}
If the above code seems to be a bit messy, don't worry. We'll explain some sections of code.
As I said previously, the function really extracts the records from the "rows" array, using a record pointer called "page," which is passed as the unique parameter. This pointer is used internally to calculate the position within the array and display the exact number of records. The lines listed below perform that operation:
for(var i=(page-1)*recsPage;i<((page-1)*recsPage)+recsPage;i++){
if(rows[i]){
// insert records as paragraph elements
var p=document.createElement('p');
p.appendChild(document.createTextNode(rows[i]));
div.appendChild(p);
}
}
Notice that we're putting each record inside <p> elements, and wrapping them with a <div> tag. The only thing left is to insert the complete updated structure into the document. To do so, I've opted to replace the existing "records" <div> element with a new one, using the expression:
recsDiv.parentNode.replaceChild(div,recsDiv);
Oops! I think that the code was pretty hard to explain, but it's worthwhile. Thus, having defined the functions to contain records and paging links, as well as for displaying paginated data, what's our next step? We need to create the paging links. That's what we'll learn to do in the next section.