JavaScript Remote Scripting: An AJAX-based Random Code Generator in Action - Dynamic link generation: taking a look at the “createLinks()” function
(Page 4 of 6 )
The reason for coding this function is rather simple. I don’t want to include any rating links in the original structure of the web page, since they’ll be added through JavaScript, specifically with the DOM. Doing so, I’m making sure that users with scripting disabled won’t be disappointed if they ever try to rate a particular article. That’s why I decided to generate rating links by using the DOM. Before I show you the definition for this new function, I’d like to clarify one point: it’s possible to build the whole voting application completely without JavaScript. However, for this particular case, I’ll use a JavaScript-based approach so you can see how remote scripting is implemented by utilizing client-side programming.
Now, let’s pay attention to the “createLinks()” function, defined in the following way:
function createLinks(){
var ps=document.getElementsByTagName('p');
if(!ps){return};
for(var i=0;i<ps.length;i++){
// create <span> elements
var sp=document.createElement('span');
// create <a> elements
var a=document.createElement('a');
a.setAttribute('href','#');
a.setAttribute('title','Rate this article!');
a.appendChild(document.createTextNode('Rate this
article!'));
sp.appendChild(a);
// assign 'onclick' event handler to <span> elements
sp.onclick=function(){
sendRequest(this,'process_input.php');
}
ps[i].appendChild(sp);
}
}
By studying the function above, it’s clear what’s happening. In simple terms, the function iterates over all the paragraph elements of the web document (remember that heading texts of articles were wrapped into paragraphs), in order to append to each of them the corresponding rating links. Once links are inserted into the web page, turn your attention to the following piece of code:
sp.onclick=function(){
sendRequest(this,'process_input.php');
}
As you can see, what I’m doing here is providing each link (wrapped into a <span> tag) with the ability to request the “process_input.php” file every time it is clicked on. Notice the call to the “sendRequest()” function, discussed in my previous article, which accepts the name of the file to be fetched, along with the link that generated the “click” event.
Now that you know how rating links are dynamically appended to the web document, it’s time to look at the processing performed on the server, for generating four-digit random codes. All you have to do is keep on reading.
Next: Server-side processing: generating four-digit random codes with PHP >>
More JavaScript Articles
More By Alejandro Gervasio