Heyyyy... I'm trying to get some AJAX going on in my website. It works FINE in IE 6, but when I try it with Mozilla FireFox, nothing happens. Can anybody see anything wrong with the following javascript code?

function makeRequest(url, divID) {
var http_request = null;
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e){
http_request = new ActiveXObject("Microsoft.XMLHTTP");
} 
if (http_request == null){
http_request = new XMLHttpRequest();
}
 
//if still cannot create HTTP REQUEST object:
if (!http_request) {
alert('Sorry. Cannot create an XMLHTTP instance. Please try again');
return false;
}
http_request.onreadystatechange = function(){ handleResponse(http_request, divID); };
http_request.open("GET", url, false);
http_request.setRequestHeader( "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT" );
http_request.send( null );
}

K, I got it working. I'm not sure which part of my code was incorrect, but it works now.

function makeRequest(url, divID) {
 var http_request = null;
    var browser = navigator.appName; 
     
    if(browser == "Microsoft Internet Explorer") 
    { 
        /* Create the object using MSIE's method */ 
        http_request = new ActiveXObject("Microsoft.XMLHTTP"); 
    } 
    else 
    { 
        /* Create the object using other browser's method */ 
        http_request = new XMLHttpRequest(); 
    } 
 //if still cannot create HTTP REQUEST object:
 if (!http_request) {
  alert('Sorry. Cannot create an XMLHTTP instance.  Please try again');
  return false;
 }
 http_request.onreadystatechange = function(){ handleResponse(http_request, divID); };
 http_request.open("GET", url, true);
 http_request.send( null );
}

I think that this line was the clincher:
http_request.open("GET", url, true);

It seems if you set the last option to false, (which forces scripts to wait until the response is received from the server), Mozilla simply says "no way, not doin it".

Hope this post will help SOMEBODY.

ROck On

This might be the answer I was looking for.

I am using false for async and Firefox wouldn't work until I installed Firebug plugin, then Firefox would work with async=false requests.

Couldn't figure out why, glad you narrowed it down :)

Wanted to add that I did some reading around different places about this subject, it seems to be a consensus that using synchronous requests is just a bad idea, the reason being you are not supposed to lock-up the users interface.

For my purposes I needed JS execution to wait for the response or my variables would be empty and the following code throwing exceptions or failing silently.

What I tested, and will do throughout my scripts, is call the function that is going to use that information from the response handling portion of the ajax request.

A working example:
( text.ajax.php returns an XML doc with a status tag and an email tag, the latter containing a string in the format: "name,email^name,email^name,email" )

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script type="text/javascript">
<!--
function HttpClient() { } // HTTPCLIENT CLASS
HttpClient.prototype = {
	// type GET,POST passed to open
	requestType:'GET',
	// when set to true, async calls are made
	isAsync:true,
	// where an XMLHttpRequest instance is stored
	xmlhttp:false,
	// what is called when a successful async call is made
	callback:false,
	// what is called when send is called on XMLHttpRequest
	// set your own function to onSend to have a custom loading
	// effect
	onSend:function()
	{
		//document.getElementById('HttpClientStatus').style.display = 'block';
	},
	
	// what is called when readyState 4 is reached, this is
	// called before your callback
	onload:function()
	{
		//document.getElementById('HttpClientStatus').style.display = 'none';
	},
	
	// what is called when an http error happens
	onError:function(error)
	{
		alert(error);
	},
	
	// method to initialize an xmlhttpclient
	init:function()
	{
		try
		{
			// Mozilla / Safari
			this.xmlhttp = new XMLHttpRequest();
		}
		catch (e)
		{
			// IE
			var XMLHTTP_IDS = new Array('MSXML2.XMLHTTP.5.0',
				 'MSXML2.XMLHTTP.4.0',
				 'MSXML2.XMLHTTP.3.0',
				 'MSXML2.XMLHTTP',
				 'Microsoft.XMLHTTP');
			var success = false;
			for (var i=0;i < XMLHTTP_IDS.length && !success; i++)
			{
				try
				{
					this.xmlhttp = new ActiveXObject
					(XMLHTTP_IDS[i]);
					success = true;
				}
				catch (e)
				{}
			}
			if (!success)
			{
				this.onError('Unable to create XMLHttpRequest.');
			}
		}
	},
	// method to make a page request
	// @param string url  The page to make the request to
	// @param string payload  What you're sending if this is a POST
	//                        request
	makeRequest: function(url,payload)
	{
		if (!this.xmlhttp)
		{
			this.init();
		}
		this.xmlhttp.open(this.requestType,url,this.isAsync);
		
		// set onreadystatechange here since it will be reset after a
		//completed call in Mozilla
		var self = this;
		this.xmlhttp.onreadystatechange = function()
		{
			self._readyStateChangeCallback();
		}
		if (this.requestType == "POST")
		{
			this.xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			this.xmlhttp.setRequestHeader("Content-length", payload.length);
			this.xmlhttp.setRequestHeader("Connection", "close");
		}
		
		this.xmlhttp.send(payload);
		
		if (!this.isAsync)
		{
			return this.xmlhttp.responseXML;
		}
	},
	
	// internal method used to handle ready state changes
	_readyStateChangeCallback:function()
	{
		switch(this.xmlhttp.readyState)
		{
			case 2:
				this.onSend();
				break;
			case 4:
				this.onload();
				if (this.xmlhttp.status == 200)
				{
					this.callback(this.xmlhttp.responseXML);
				}
				else
				{
					this.onError('HTTP Error Making Request: ' + '[' + this.xmlhttp.status + ']' + ' ' + this.xmlhttp.statusText);
				}
				break;
		}
	}
}

var client = new HttpClient();// create an instance of the object
client.isAsync = true;// 
var company_email = null;// declare the global
var http_status = null;

function get_email_list()
{
	client.requestType = "GET";
	// function to handle completed calls
	client.callback = function(XMLresult)
	{
		if (XMLresult.getElementsByTagName("status"))// did XML page create a 'status' element?
		{
			http_status = XMLresult.getElementsByTagName("status")[0].childNodes[0].nodeValue;
		}else{// if no 'status' element was returned, set global http_status to FAILED NO STATUS
			http_status = "FAILED NO STATUS";
			alert(http_status);
			return;
		}
		if (http_status == "SUCCESS") {// if we got a SUCCESS in 'status' element, put row data in global variable
			// use of split("^") gives us an array of "name,email" pairs.
			company_email = XMLresult.getElementsByTagName("email")[0].childNodes[0].nodeValue.split("^");
			// call the function only after a successfull request is made
			build_contact_list();
		}
		else
		{
			alert(http_status);
		}
	}
	client.makeRequest('test.ajax.php?sid='+Math.random(),null);
	return;
}

function build_contact_list()// called from the request handler only on good responses
{
	var cm = document.getElementById("contact_menu"); // get the select element
	
	// remove all options from this select element
	while ( cm.options.length )
	{
		cm.remove(cm.options[0]);
	}
	
	for ( var i = 0; i < company_email.length; i++ )
	{
		var newOpt=document.createElement('option');
		// now seperate the name from the email address
		var tmp = company_email[i].split(",");
		newOpt.text=tmp[0];// set the persons name as the text of the option element
		try
		{
			cm.add(newOpt,null); // standards compliant
		}
		catch(ex)
		{
			cm.add(newOpt); // IE only
		}
		cm.options[i].value = tmp[1];// set the email address as the value of the option element
		cm.selectedIndex = 0;
	}
	return;
}

function request_email()
{
	http_status = null;
	get_email_list(); // make the call and run away
	return;

}
-->
</script>
</head>

<body>
	<div>
		<select id="contact_menu">
			<option></option>
		</select>
		<br>
		<button type="button" onClick="request_email()">Build The Menu</button>
	</div>
</body>
</html>

For my current project I really need to stop execution of any script until any ajax request are complete, but I will do that another way so I can avoid the problem with Firefox not liking synchronous requests.

The URL domain matters. Firefox does not allow doing a GET (or any other verb) from a different domain than the domain of the page itself. Cross Domain Scripting security. IE will allow it under some circumstances - liek if you are running an HTML page locally.

hi kramzkramz,

Is there any solution for this problem? any work around?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.