Ajax code not working in Firefox
I have a small Ajax code that works very well in IE but do not work under Firefox. I have no error in Firefox console.
Code:
function get_Xhr()
{
if (window.XMLHttpRequest) // Purpose of the current window
{
xhr = new XMLHttpRequest(); // Firefox, Safari, ...
}
else
if (window.ActiveXObject) // Version Active
{
xhr = new ActiveXObject("Microsoft.XMLHTTP" ); // Internet Explorer
}
}
function ajaxclient()
{
get_Xhr();
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4 && xhr.status == 200)
{
document.getElementById('testt').innerHTML = xhr.responseText;
}
}
xhr.open("POST",'ajax/ajax_ajout_client.php',true);
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send("cocl="+document.form_ajout_client.name.value);
}
Re: Ajax code not working in Firefox
Quote:
function ajaxclient()
{
get_Xhr();
The get_Xhr() serves no function, since you can return any value. If you instantiate objects without sending them back (your variable is local) that will not work, it is clear and logical
Instead use:
Code:
var xhr = get_Xhr ();
Re: Ajax code not working in Firefox
You can also add a test for Msxml2.XMLHTTP:
Code:
function get_Xhr()
{
var xmlHTTP;
try{xmlHTTP = new XMLHttpRequest();}
catch(e) {
try{xmlHTTP = new ActiveXObject("Msxml2.XMLHTTP" );}
catch(e) {
try{xmlHTTP = new ActiveXObject("Microsoft.XMLHTTP" );}
catch(e) {
alert("Your browser does not support AJAX!" );
return false;
}
}
}
return xmlHTTP;
}
Re: Ajax code not working in Firefox
After giving the second thought to your case, I think you should go with
Code:
var xhr = function ()
{
if (window.XMLHttpRequest) // FIREFOX
return new XMLHttpRequest ();
if (window.ActiveXObject) // IE old and new
{
var o;
try { o = new ActiveXObject ("Msxml2.XMLHTTP" ); }
catch (e) { o = new ActiveXObject ("Microsoft.XMLHTTP" ); }
return o;
}
alert ("No support for XHR!" );
return false;
}
it is probably more complete because it manages the different cases for IE
Re: Ajax code not working in Firefox
The following example should work mate
<html>
<body>
<script type="text/javascript">
function ajaxFunction()
{
var xmlHttp;
try
{
// Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
}
</script>
<form name="myForm">
Name: <input type="text" name="username" />
Time: <input type="text" name="time" />
</form>
</body>
</html>