The time it takes to execute the response goes up by more than 3x on my development server when using synchronous mode. With async on it takes anywhere from 4ms to 6ms according to firefox(firebug). And with the script waiting to sync it takes anywhere from 18ms to 21ms. Doesn't seem that bad, but if this was a production server under heavy load it, those numbers would probably get a lot worse.
So as for my solution I think I'll just go with async and just add an extra parameter to my init function. So along with the method and url I'm also going to be passing the object that I want to update with my responseText.
Shouldn't I leave that code to support IE 6? Also I'm not quite sure how to add a status check? I'm assuming that I'm doing the check before it gets to readyState 4.
PHP Code:
if (AJAX.xmlHttp.readyState<4){
if (AJAX.xmlHttp.status="404"){ AJAX.xmlHttp.abort(); } }
Is that what your talking about? If not could you give me an example? The more I think about it. The more it make sense to do something like that.
Location: Los Angeles, CA Original Location: Philippines
Posts: 10,241
Thanks: 0
Thanked 112 Times in 111 Posts
AJAX wrapper functions should be generic and reusable. Putting specific requirements as below will render it useless to other functionalities that need AJAX.
Code:
stateChanged : function(){
if (AJAX.xmlHttp.readyState==4){
AJAX.divId.innerHTML=AJAX.xmlHttp.responseText;
}
},
You should add a callback function in the init function in order for the onreadystatechange handler to call it once the response is available.
Code:
AJAX = {
xmlHttp:'',
init : function(methodType, url, callback){
AJAX.xmlHttp=AJAX.getXmlHttpObject();
if (AJAX.xmlHttp==null){
alert ("Your browser does not support AJAX!");
return;
}
AJAX.xmlHttp.open(methodType,url,true);
AJAX.xmlHttp.onreadystatechange=function(){AJAX.stateChanged(callback)};
AJAX.xmlHttp.send(null);
},
stateChanged : function(callback){
if (AJAX.xmlHttp.readyState==4){
if (AJAX.xmlHttp.status == 200) {
if (callback) callback(AJAX.xmlHttp.responseText);
}
}
},
...
}
function myCallbackFunction(responseText){
alert(responseText);
//do what you want with the response
}
var response=AJAX.init("GET","./test.php", myCallbackFunction);
Location: Los Angeles, CA Original Location: Philippines
Posts: 10,241
Thanks: 0
Thanked 112 Times in 111 Posts
Doing what you suggested would immediately call the stateChanged handler and assign the return of that function to onreadystatechange. You don't want to do that. What you want to do is as assign onreadystatechange to a function pointer.
What I did was I assign the onreadystatechange to an anonymous function. You can also assign it to a named function just like what you did here.
Take note that you didn't put () to the stateChanged function. If you put (), it would be immediately executed and not assign it to a handler. If your function has parameters, normally you would use an anonymous function. Thus the solution: