Helpful Information
 
 
Category: Ajax and Design
Ajax and Firefox

Hello,

I cant figure out why the code below is not working in Firefox it works fine in IE?



function sndReq(action) {
http.open('get', 'page.php?action='+action);
http.onreadystatechange = function() {
switch(http.readyState){
case 1:
alert(1);
break;
case 2:
alert(2);
break;
case 3:
alert(3);
break;
case 4:
alert(4);
break;
};
}
http.send(null);
}


In IE I get alerts for all 4 states but in FireFox I only get alert 4 what gives..

added code for knowledge



var http_request = false;
var http = false;
function getHTTPObj() {
try {
http_request = new XMLHttpRequest();
}
catch (e) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
http_request = false;
alert("Your Browser does not work with Web 2.0!\nPlease Update");
}
}
}
return http_request;
}

var http = getHTTPObj();

I had never done much with the states 1-3 before since I read they mean slightly different things in different browsers. But doing some tests and looking at your code I think the problem is that for some reason the default ajax request on firefox is synchronous (I thought it was async).

So you need to add a third parameter to your open command with true as the value.

http.open('get', 'page.php?action='+action, true);

That makes the onreadystatechange fire for 1-3 in FF as well.

david_kw

hello,

dear, much better to pass the variable in send like:

sndreq.send(action=action);

try to use the following code, it is tested on safari, FF and IE:




var http_request = false;

if (window.XMLHttpRequest)
{
// Mozilla, Safari, ...
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType)
{
http_request.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject)
{
// IE
try
{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e){}
}
}
if (!http_request)
{
alert('Giving up :( Cannot create an XMLHTTP instance');

return false;
}



regards

Hello,

Thankyou for the reply.

That worked great. But I am curious where would I look into checking to see about the ajax being syncronous and not asyncronous? Is this something fixable? I would rather it be asyncronous.

That 3rd parameter to the open() function determines it. If true it is async, false is sync. If you pass only two parameters it is supposed to be async (according to my documentation) and appears to be in IE, but in FF the default is sync apparently.

Long and short. Always pass true for the 3rd parameter and you should be good to go with asynchronous calls.

david_kw










privacy (GDPR)