DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Chris has posted 1 posts at DZone. View Full User Profile

Simple Javascript XHR Object With Fix For Missing Onreadystatechange Event In Firefox (for Synchronous Calls)

04.21.2008
| 9259 views |
  • submit to reddit
        This code fixes the issue in Firefox where the onreadystatechange event is not called for synchronous XHR requests. It is based on the XHConn script from http://xkr.us/code/javascript/XHConn/, patched with the fix documented at http://lukav.com/wordpress/2007/04/12/firefox-firebug-and-synchronos-calls-problem/

/** XHConn - Simple XMLHTTP Interface - bfults@gmail.com - 2005-04-08        **
 ** Code licensed under Creative Commons Attribution-ShareAlike License      **
 ** http://creativecommons.org/licenses/by-sa/2.0/                           **/
/**
 * Modified slightly from original to support synchoronous transactions
 * CDB 2007-05-16, 2007-06-05
 */

function XHConn()
{
	var xmlhttp, bComplete = false;
	try { xmlhttp = new ActiveXObject("Msxml2.XMLHTTP"); }
	catch (e) { try { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
	catch (e) { try { xmlhttp = new XMLHttpRequest(); }
	catch (e) { xmlhttp = false; }}}
	if (!xmlhttp) return null;
	this.connect = function(sURL, sMethod, sVars, fnDone, bAsynch)
	{
		if (!xmlhttp) return false;
		bComplete = false;
		sMethod = sMethod.toUpperCase();

		if (bAsynch == null) bAsynch = true; //treat asynch as an optional argument

		try {
			if (sMethod == "GET")
			{
				xmlhttp.open(sMethod, sURL+"?"+sVars, (bAsynch == true));
				sVars = "";
			}
			else
			{
				xmlhttp.open(sMethod, sURL, (bAsynch == true));
				xmlhttp.setRequestHeader("Method", "POST "+sURL+" HTTP/1.1");
				xmlhttp.setRequestHeader("Content-Type",
					"application/x-www-form-urlencoded");
			}

			xmlhttp.onreadystatechange = function(){
				if (xmlhttp.readyState == 4 && !bComplete)
				{
					bComplete = true;
					fnDone(xmlhttp);
				}
			};
			xmlhttp.send(sVars);

			/**
			 * Firefox <= 2.0.0 doesn't fire onreadystatechange for synchronous requests.
			 * See http://lukav.com/wordpress/2007/04/12/firefox-firebug-and-synchronos-calls-problem/
			 */
			var isGecko = (document.addEventListener) ? true : false;
			try {
				if (!bAsynch && isGecko && xmlhttp.onreadystatechange == null) {
					bComplete = true;
					fnDone(xmlhttp);
					return true;
				}
			}
			catch (e) { return false; }
			/**
			 * End synchronous request patch
			 */
		}
		catch(z) { return false; }
		return true;
	};
	return this;
}