A general purpose JavaScript ajax object
During the years I needed to use always more often ajax implementations in web design. There are several reasons to use this technology but the first is for sure that reloading a page just to update a small quantity of data is really annoying and looks really “not professional”.
So the first thing that you can realize in approaching ajax is that you need to write code using JavaScript, HTML and PHP or other serve side languages, and you will feel for sure much better if you can use something standard: for example a library.
Actually, there are really tons of libraries, scripts and codes that can help you in your job, but I never found once that was exactly as I like. So I wrote something that I want to share here.
Te requirements I had in mind writing the code were:
– Object oriented
– Flexible
– Multiple instances capable
– Small, smaller, smallest
I’m not sure if I met the last requirement, but I guess I did it for the others.
Object oriented
It is. No more thing to say
Flexible
I think yes, but what does it mean “flexible”. Of course it is not possible to think that it will fit any possible use, but will cover at least the following wide range of situations: anytime you have to manage information coming from a server to be placed inside a <div> or <span> (or similar) tag, then you can use this object.
One more meaning of “flexible” is that you can also reuse it also outside this framework, with very few and easy modifications.
Multiple Instances
Generally speaking, you can use how may instances of the object, is just a matter of browser or of server whether it can manage a huge numbers of requests. But, do you really need something like that?
The ajaxObject object
First of all I have to thank this Article, since part of code is coming from this idea and I suggest everybody to read, since it’s really well written.
Using the object is very simple and common.
Firstly you have to initiate a new instance, then you can make the request. That’s all.
You don’t need to create code to manage timeout, a very simple (but effective) engine to generate a kind of “progress bar” is available, and the result can be automatically placed in you <div> or <span>
But, if you need something more advanced, you have access to hooks for result and timeout callback functions.
The script
[cc lang=”javascript”]
/* *********************************************************
Version 0.3
Rel. Notes 0.2 added showprogressbar property to enable/disable the progress bar;
0.3 bug fix to close progress bar was called showprogress.stop() that dosen’t exist instead of showprogressbar.stop();
AJAX object with multiple instaces support
Parameters: url the url of ajax request i.e. the server
defOutId the ID of the HTML section where output will be displayed, if null no output
callbackFunction function that is called after response has been received. can be null or not present
Properties timeout in milliseconds for request
stattusbar true or false enable or disable the use of browser status bar
Methods update(passData,postMethod) set the call parameters, the post method and make the call.
*********************************************************/
function ajaxObject(url, defOutId, callbackFunction)
{
var that=this;
this.timeout=10000; // Default timeout is 10 Seconds
this.statusbar=true; // Set to false if you don’t want activities to be displayed on browser status bar
this.bartimer=125; // millisecond of progress bar timer.
this.updating = false; // Used to verify if a request is already running
this.urlCall = url; // Ajax server url
this.defOut=defOutId; // Set the delault output ID
this.showprogressbar=true; //So progressbar is shown
this.callback = callbackFunction || function () { }; // Set the callback function activated when request is completed
// Define the function that will be called on request timeout
var toutfunc= function()
{
if (that.updating) //if there is a pending reqyest abort AJAX request
{
that.AJAX.abort(); // abort pending request
that.updating=false; // a new call can be done
that.showprogressbar.stop(); // No more need for progress bar
if (that.defOut) {document.getElementById(that.defOut).innerHTML=”Timeout”;} // Write the message
}
}
// Set timers
this.ttimeout= new timerObject(this.timeout,toutfunc,null); //Set timeout function
this.ttimeout.repeat=0; // Just one shot
this.progressbar=null;
if (this.showprogressbar) this.progressbar= new timerObject(this.bartimer,null,this.defOut); //Set timer for progress bar
// Now create an XML HTTP Request
this.AJAX = null;
if (window.XMLHttpRequest) { this.AJAX=new XMLHttpRequest();} // Not MS Browser
else { this.AJAX=new ActiveXObject(“Microsoft.XMLHTTP”); } //MS Browser
}
/* *********************************************************
AJAX execution update method Execute a call.
Parameters: passData parameters of the call.
postMethod
*********************************************************/
ajaxObject.prototype.update = function(passData,postMethod)
{
var that=this;
if (this.updating) { return false; } // request already pending, non need to repeat
if (this.AJAX==null) { alert(“AJAX not supported by browser”); return false; } // AJAX not supported
this.AJAX.onreadystatechange = function() //This function will be called any time AJAX status changes
{
if (that.AJAX.readyState==4)
{
if (that.progressbar) that.progressbar.stop(); // No more need for progress bar
that.ttimeout.stop(); // Disable timeout
if (that.statusbar) window.status=”Done!”; // Update the browser status bar
if (that.defOut)
{
document.getElementById(that.defOut).innerHTML=that.AJAX.responseText;
document.getElementById(that.defOut).style.visibility=”visible”;
} //Write the result
that.callback(that.AJAX.responseText,that.AJAX.status,that.AJAX.responseXML); // Finally cal an external function
that.updating=false; // Now a new call can be done
}
}
this.updating = new Date(); //Used to prevent cache errors adding this to the request, so the request will be new anytime
if (/post/i.test(postMethod)) // POST method
{
var uri=this.urlCall+’?’+this.updating.getTime();
this.AJAX.open(“POST”, uri, true);
this.AJAX.setRequestHeader(“Content-type”, “application/x-www-form-urlencoded”);
this.AJAX.setRequestHeader(“Content-Length”, passData.length);
this.AJAX.send(passData); //Send the request
}
else // GET method (default)
{
var uri=this.urlCall+’?’+passData+’×tamp=’+(this.updating.getTime());
this.AJAX.open(“GET”, uri, true);
this.AJAX.send(null); //Send the request
}
this.ttimeout.start(); //Start timeout timer
if (this.showprogressbar) this.progressbar.start(); //Start the progress bar
if (this.statusbar) window.status=”Processing “+ uri ; //Update browser status bar
return true;
}
/* *********************************************************
timer Object used for timeout and progress bar in ajax object.
Multiple instances are supported
Parameters: timeout in milliseconds
timerfunc function called when timer expires can be null
outid id of where to display the progress bar, can be null.
properties
counter: incremented each time timeout expires
timeout: timeout
repeat: if 1 any time timer expires is resetted, if 0 just one shot.
progbar: array of elements to be displayed sequentially as a progress bar
methods
start(): Activate the timer
stop(): stop the timer
*********************************************************/
function timerObject(timeout,timerfunc,outid)
{
var that=this;
this.counter=0; //Initialize the counter
this.timeout=timeout; // Set timeout value (milliseconds)
this.repeat=1; // So the timer will be repeted
this.start = function() { that.timer=setTimeout(this.TimerCall, this.timeout); } //Function to activate timer
this.stop = function() { clearTimeout(this.timer); } //Function to stop time
this.tfunc = timerfunc || function () { }; //Set the timer function
// this.progbar=new Array(“.”,”..”,”…”,”….”,”…..”,”….”,”…”,”..”,”.”);
// The progress bar
this.progbar=new Array(“|”,”||”,”|||”,”||||”,”|||||”,”||||”,”|||”,”||”,”|”);
this.TimerCall=function() //Timer event function
{
var chars=that.progbar;
that.counter++; //Increase counter
//Display new position of progress
if (outid) document.getElementById(outid).innerHTML=”Processing “+chars[that.counter % chars.length];
that.tfunc(); //Call timer function
if (that.repeat) that.start(); // If needed restart the timer
}
}
[/cc]
Well, I think that the code is well documented, so you can have a look and easily understand how it works. So In the next few lines, I will make some examples to explain hot to use it.
Note that the javascript code shall be placed inside <head></head> tags.
The firs thing, as I said, is to create an instance of the object. This is very simple to do, you just need to write a very small code that you can place wherever you prefer inside your html:
[cc lang=”javascript”]
<script type=”text/javascript” >
var af1=new ajaxObject(“ajax.php”,”ID1″);
</script>
[/cc]
This code is setting the general parameters of your object. “ajax.php” is your server side application while “ID1” is the id of you <span>,<div>, … tag, where answer coming from server will be placed.
Now you have an ajax object called “af1”.
Next, you have to create the space where to place the results:
[cc lang=”html”]
<div id=”ID1″></div>
[/cc]
will do exactly this.
Finally you need something to generate the call. You can use any possible event to call the upload method. For example you can use the “onload” in the <body> tag, or the “onclick” wherever it is allowed.
[cc lang=”html”]
<body onload=’af1.update(“t=1”);’>
[/cc]
will make the request when the page is loaded
or
[cc lang=”html”]
<p onclick=’af1.update(“t=1”);’>Click to start ajax request 2 </p>
[/cc]
will make the request any time you will click on the test. The update method first parameter are the parameters passed to the server side application.
That’s really all and it’s free.
Below I paste an example of html page and a small server side application to test the script.
[cc lang=”html”]
<html>
<head>
<script src=”ajax.js” type=”text/javascript”></script>
<script type=”text/javascript” >
var af1=new ajaxObject(“ajax.php”,”ID1″);
var af2=new ajaxObject(“ajax.php”,”ID2″);
af2.statusbar=false;
function startAjax()
{
af1.update(“t=15”);
af2.update(“t=1”);
}
</script>
</head>
<body onload=’startAjax();’>
<div><span onclick=’af1.update(“t=15″);’>Click to start ajax request 1 </span><span id=”ID1″>First</span></div>
<div> <span id=”ID2”>Second</span></div>
</body></html>
[/cc]
PHP very small application:
[cc lang=”php”]
<?php
extract($_REQUEST);
sleep($t);
echo ‘This is server response’;
?>
[/cc]
Updates
On rel. 0.2 I’ve added a property for ajaxObject called showprogressbar that enable or disable the progressbar.
This can be useful if you periodically refresh the content and want to keep displayed the old one while retrieving the new one.
0.3 Fixed a bug on progressbar