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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | /* ********************************************************* 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+'&timestamp='+(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 } } |
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:
1 2 3 | <p style="text-align: justify;"><script type="text/javascript" ></p> <p style="padding-left: 30px; text-align: justify;">var af1=new ajaxObject("ajax.php","ID1");</p> <p style="text-align: justify;"></script></p> |
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:
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.
will make the request when the page is loaded
or
1 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <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></em></p> <em></head></em> <em><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></em> <em></body></html> </em> |
PHP very small application:
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