Dynadot โ€” .com Registration $8.99

[Resolved] Simple Javascript error

Spaceship Spaceship
Watch
Impact
209
Simple javascript error

Hi all.

I am just working myway adding some ajax to a page however come across a silly snag.

I have the following code (nowhere near finished but need a bug fixed before I continue).

Code:
var xmlhttp;
var fields;

function createXMLHttpRequest()
{
	if(window.ActiveXObject)
	{
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else if(window.XMLHttpRequest)
	{
		xmlhttp = new XMLHttpRequest();
	}
}
function get_form(str, field)
{
	createXMLHttpRequest();
	fields = field;
	xmlhttp.onreadystatechange = callback;
	url = "/admin/test.php";
	url = url+"?type="+str;
	xmlhttp.open("GET", url, true);
	xmlhttp.send(null);
}
function callback()
{
	if(xmlhttp.readystate == 4)
	{
		if(xmlhttp.status == 200)
		{
			document.getElementById(fields).innerHTML=xmlhttp.responsetext;
		}
		else
		{
			document.getElementById(fields).innerHTML='There has been a problem';
		}
	}
}

In internet explorer this works 100% with no issues however when I try it in firefox nothing happens.

I have tried putting an alert before the 1st if in callback which worked and showed the content of fields however when I put the same alert in the if no alert happens at all (even though the http request is carried out). If I hard code the fields content into getElementById it will work 100% but I wish to do it more dynamically as it seems a waste to write a callback multiple times when I will just be doing the same thing.

Anyone got any idea what is causing this. I am assuming it is a scope issue which IE and firefox treat differently.
 
Last edited:
0
•••
The views expressed on this page by users and staff are their own, not those of NamePros.
AfternicAfternic
Since this is in the SE section I figured I would let you know what search engines do not index javascript. ;)
 
0
•••
firstly some search engines can use javascript now (google have been playing with that for some time)

secondly it doesn't matterasthis is going to be in an area in which you NEED to be logged in so search engines will not see it anyway.

Oh and I have no idea why I posted itin the SE section. Must have pressed the wrong section when going to post (i subscribeto both the SE section as well as the programming section).
 
0
•••
xmlhttp.onreadystatechange = callback();
or
xmlhttp.onreadystatechange = new callback();

also you need the debugger for ff it'll tell you straight up whats wrong
 
0
•••
no sorrythat is wrong blacknet.

Read the documentation for onreadystatechange you do not assign it the function you only assign itthe nameof the function (in fact I even tried that earlier and it caused errors instead)
 
0
•••
see I oo thus
xmlhttp.onreadystatechange = new object.method();
works :)

here.. have a handler

Code:
/*

http handler, single object - many requests (example at bottom)
Tested:
		1000 executes per second, no cache hits for 20 minutes
		alternating data microtime string | phpinfo() - 1.2million+ executes, no memory leaks
*/

function httpHandler() {
	this.HTTPRequestArray = new Object();

/*
=====================================================
	HTTP Request Array Controls
	=====================================================
*/
	this.setRequest = function(httpMethod, requestURI, requestReference) {
		httpMethod = httpMethod.toUpperCase();
		if(this.verify_httpMethod(httpMethod)) {
			this.HTTPRequestArray[requestReference] = new Object();
			this.currentRequest = this.HTTPRequestArray[requestReference];
			this.currentRequest.HTTPRequestHeaders = new Object();
			this.currentRequest.HTTPReturnDump = false;
			this.currentRequest.HTTPRequestMethod = httpMethod;
			this.currentRequest.HTTPRequestURI = requestURI;
			this.createHeaders();
			this.setDefaults();
		} else {
			alert('The value: '+httpMethod+' :is not supported by this version of HTTPRequest');
		}
	}

	this.removeRequest = function(requestReference) {
		if(this.HTTPRequestArray[requestReference]) {
			delete this.HTTPRequestArray[requestReference];
		} else {
			alert('The Request Reference: '+requestReference+' :was not found within the object');
		}
	}
/*
=====================================================
	Request Detail Configuration
	=====================================================
*/	
	this.setReturn = function(returnDump, requestReference) {
		if(requestReference) {
			this.currentRequest = this.HTTPRequestArray[requestReference];
		}
		this.currentRequest.HTTPReturnDump = returnDump;
	}
	
	this.setEntity = function(entity, requestReference) {
		if(requestReference) {
			this.currentRequest = this.HTTPRequestArray[requestReference];
		}
		if(in_array(this.currentRequest.HTTPRequestMethod, Array('POST','PUT'))) {
			entity = trim(entity);
			this.currentRequest['HTTPEntity'] = entity;
			this.setHeaderValue('content-length', entity.length);			
		} else {
			alert('The selected Request Method: '+this.currentRequest.HTTPRequestMethod+' :does not support entities');
		}
	};	
/*
=====================================================
	HTTP Request Executor
	=====================================================
*/		
	this.execute = function(removeRequests) {
		for(HTTPRequestURI in this.HTTPRequestArray) {
			this.currentRequest = this.HTTPRequestArray[HTTPRequestURI];
			if((this.currentRequest.HTTPRequestMethod) && (this.currentRequest.HTTPRequestURI)) {
				if (window.XMLHttpRequest) {
			/*	Standard XMLHTTPRequest Initialisation */
					this.currentRequest.HTTPRequest = new XMLHttpRequest();
					this.currentRequest.Async = true;
				} else if (window.ActiveXObject) {
			/*	Old IE XMLHTTP Object */
					this.currentRequest.HTTPRequest = new ActiveXObject("Microsoft.XMLHTTP");
					this.currentRequest.Async = false;
				}
			/* only proceed is the XMLHTTP(Request) Object Loaded */
				if (this.currentRequest.HTTPRequest) {
				/* open up the connection */
					this.currentRequest.HTTPRequest.open(this.currentRequest.HTTPRequestMethod,this.currentRequest.HTTPRequestURI,this.currentRequest.Async);
				/*	Set all Request Headers that have values set */
					for(headerField in this.currentRequest.HTTPRequestHeaders) {
						if(this.currentRequest.HTTPRequestHeaders[headerField].value) {
							this.currentRequest.HTTPRequest.setRequestHeader(headerField, this.currentRequest.HTTPRequestHeaders[headerField].value);
						}
					}
					
					try {
					/* ff */
						this.currentRequest.HTTPRequest.toSource();
						this.currentRequest.HTTPRequest.onreadystatechange = new this.recieveHTTPResponse();
					} catch(err) {
					/* the joys of IE... */
						try {
						/* IE7 */
							this.currentRequest.HTTPRequest.HTTPReturnDump = http.currentRequest.HTTPReturnDump;
							this.currentRequest.HTTPRequest.tempHandler = new this.recieveHTTPResponse(true);
							this.currentRequest.HTTPRequest.onreadystatechange = this.currentRequest.HTTPRequest.tempHandler.handleEv;
						} catch(err2) {
						/* IE6 non Async!!! */
							this.currentRequest.HTTPResponseHandler = new this.recieveHTTPResponseX();
							this.currentRequest.HTTPRequest.onreadystatechange = this.currentRequest.HTTPResponseHandler.handleEv;
						}
					}
									
					if(this.currentRequest.HTTPEntity) {
					/* 	Send the entity (post string) if we have one */
						this.currentRequest.HTTPRequest.send(this.currentRequest.HTTPEntity);
					} else {
					/*	Send with no entity */
						this.currentRequest.HTTPRequest.send('');
					}
				} else {
					alert('Your User-Agent failed to initialise HTTPReqest');
				}
			}
		}
		if(removeRequests) {
			this.HTTPRequestArray = new Object();	
		}
	};
/*
=====================================================
	HTTP Transport Response Handlers
	=====================================================
*/	
	this.recieveHTTPResponse = function(OldStylee) {
		if(!OldStylee) {
		/* FF Safari Etc */
			this.CurrentObj = http.currentRequest.HTTPRequest;
			this.HTTPReturnDump = http.currentRequest.HTTPReturnDump;
			this.handleEvent = function() {

				if (this.CurrentObj.readyState==4) {
				  if (this.CurrentObj.status==200) {
					if(this.HTTPReturnDump) {
						if(this.HTTPReturnDump.prototype) {
							this.HTTPReturnDump(this.CurrentObj.responseText);
						} else {
							document.getElementById(this.HTTPReturnDump).innerHTML = this.CurrentObj.responseText;
						}
					} else {
						alert(this.CurrentObj.responseText);
					}
				  } else {
					if(this.HTTPReturnDump.prototype) {
						this.HTTPReturnDump(false);
					} else {
						alert("Problem retrieving XML data");
					}
				  }
				}
			};
		} else {
		/*	IE7, have to throw back a function as onreadystatechange doesn't work on objects.. */
			this.handleEv = function() {
				if (this.readyState==4) {
				  if (this.status==200) {
					if(this.HTTPReturnDump) {
						if(this.HTTPReturnDump.prototype) {
							this.HTTPReturnDump(this.responseText);
						} else {
							document.getElementById(this.HTTPReturnDump).innerHTML = this.responseText;
						}
					} else {
						alert(this.responseText);
					}
				  } else {
					if(this.HTTPReturnDump.prototype) {
						this.HTTPReturnDump(false);
					} else {
						alert("Problem retrieving XML data");
					}
				  }
				}
			};
		}
	};
	
	this.recieveHTTPResponseX = function() {
		/* IE6 */
		this.handleEv = function() {
			var CurrentObj = http.currentRequest;
			if (CurrentObj.HTTPRequest.readyState==4) {
			  if (CurrentObj.HTTPRequest.status==200) {
				if(CurrentObj.HTTPReturnDump) {
					if(CurrentObj.HTTPReturnDump.prototype) {
						CurrentObj.HTTPReturnDump(CurrentObj.HTTPRequest.responseText);
					} else {
						document.getElementById(CurrentObj.HTTPReturnDump).innerHTML = CurrentObj.HTTPRequest.responseText;
					}
				} else {
					alert(CurrentObj.HTTPRequest.responseText);
				}
			  } else {
				if(CurrentObj.HTTPReturnDump.prototype) {
					CurrentObj.HTTPReturnDump(false);
				} else {
					alert("Problem retrieving XML data");
				}
			  }
			}
		};
	};
/*
=====================================================
	Initial VALID Object Data Construction
	=====================================================
*/
	this.setDefaults = function() {
		if(this.currentRequest.HTTPRequestMethod == 'GET') {
			this.currentRequest.HTTPRequestMethod = 'POST';
			this.setEntity('a');
		}
		
		if(this.currentRequest.HTTPRequestMethod == 'POST') {
			this.setHeaderValue('Content-Type','application/x-www-form-urlencoded');
		}
		if((this.currentRequest.HTTPRequestHeaders['Cache-Control']) && (this.currentRequest.HTTPRequestHeaders['Cache-Control']['value'])) {
			if(this.currentRequest.HTTPRequestHeaders['Cache-Control']['value'] == 'no-cache') {
				this.setHeaderValue('Pragma','no-cache');
			}
		}
	};
/*
=====================================================
	Data Transformation Functions
	=====================================================
*/
	/*	Return the current gmt Date and Time formatted as per the RFC-822 specification */	
	this.rfc822Date = function() {
		var rfc822DateNow = new Date();
		return rfc822DateNow.toUTCString();
	};
	/*	Format the inputted header name to be consistent with the RFC 2616 Guidlines */	
	this.headerNameFormat = function(strin) {
		var strArray = strin.split("-");
		for(subs in strArray) {
			strArray[subs] = strArray[subs].toUpperCase().substr(0,1)+strArray[subs].toLowerCase().substr(1);
		}
		return strArray.toString().replace(',','-');
	};
	/* HTTP Method Validation */
	this.verify_httpMethod = function(strin) {
		return in_array(strin, Array('PUT','POST','GET','HEAD','OPTIONS','TRACE'));
	}
/*
=====================================================
	Request Header Field Load and Value Set Functions
	=====================================================
*/
	/*	Set the value of the specified header */	
	this.setHeaderValue = function(headerName, value) {
		headerName = this.headerNameFormat(headerName);
		if(this.currentRequest.HTTPRequestHeaders[headerName]) {
			this.currentRequest.HTTPRequestHeaders[headerName].value = value;
		} else {
			alert('The specified header: '+headerName+' :is not available in this version of HTTPRequest');
		}
	};
	/*	make a header available for use in the current request */	
	this.setHeaderItem = function(fieldName,fieldValues) {
		this.currentRequest.HTTPRequestHeaders[fieldName] = new Object();
		for(var fieldValIndex in fieldValues) {
			this.currentRequest.HTTPRequestHeaders[fieldName][fieldValIndex] = fieldValues[fieldValIndex];
		}
	};
/*
=====================================================
	Available HTTP Request Header Field Definition
	=====================================================
*/
	/*	set the array structure that forms the basis for the current request
		define and load all the relevant HTTP Request fields based on the Request Method */
	this.createHeaders = function() {
	/* General-Header */
		this.setHeaderItem('Cache-Control',	{
										'required' 	: false,
										'headType'	: 'General-Header'}
							);
		this.setHeaderItem('Connection',	{
										'required' 	: false,
										'headType'	: 'General-Header'}
							);
		if(in_array(this.currentRequest.HTTPRequestMethod, Array('PUT','POST'))) {
			this.setHeaderItem('Date',	{
										'required' 	: false,
										'headType'	: 'General-Header'}
							);
		}
		this.setHeaderItem('Pragma',	{
										'required' 	: false,
										'headType'	: 'General-Header'}
							);
		if(in_array(this.currentRequest.HTTPRequestMethod, Array('PUT','POST'))) {
			this.setHeaderItem('Transfer-Encoding',	{
										'required' 	: false,
										'headType'	: 'General-Header'}
							);
		}
		this.setHeaderItem('Upgrade',	{
										'required' 	: false,
										'headType'	: 'General-Header'}
							);
		this.setHeaderItem('Via',		{
										'required' 	: false,
										'headType'	: 'General-Header'}
							);
	/* Request-Header */						
		this.setHeaderItem('Accept',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('Accept-Charset',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('Accept-Encoding',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('Accept-Language',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('Authorization',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('Expect',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('From',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('Host',	{
										'required' 	: true,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('If-Match',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('If-Modified-Since',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('If-None-Match',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('If-Range',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('If-Unmodified-Since',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		if(in_array(this.currentRequest.HTTPRequestMethod, Array('TRACE','OPTIONS'))) {
			this.setHeaderItem('Max-Forwards',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		}
		if(this.currentRequest.HTTPRequestMethod == 'GET') {
			this.setHeaderItem('Range',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		}
		this.setHeaderItem('Referer',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('TE',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
		this.setHeaderItem('User-Agent',	{
										'required' 	: false,
										'headType'	: 'Request-Header'}
							);
	/* Entity-Header */
		if(in_array(this.currentRequest.HTTPRequestMethod, Array('PUT','DELETE'))) {
			this.setHeaderItem('Allow',	{
										'required' 	: false,
										'headType'	: 'Entity-Header'}
							);
		}
		if(in_array(this.currentRequest.HTTPRequestMethod, Array('GET','PUT','POST'))) {
			this.setHeaderItem('Content-Encoding',	{
										'required' 	: false,
										'headType'	: 'Entity-Header'}
							);
			this.setHeaderItem('Content-Language',	{
										'required' 	: false,
										'headType'	: 'Entity-Header'}
							);
			this.setHeaderItem('Content-Length',	{
										'required' 	: true,
										'headType'	: 'Entity-Header'}
							);
			this.setHeaderItem('Content-MD5',	{
										'required' 	: false,
										'headType'	: 'Entity-Header'}
							);
			this.setHeaderItem('Content-Range',	{
										'required' 	: false,
										'headType'	: 'Entity-Header'}
							);
			this.setHeaderItem('Content-Type',	{
										'required' 	: true,
										'headType'	: 'Entity-Header'}
							);
		}
	};
}

var http = new httpHandler();
/*
example

http.setRequest('POST','formprocess.php','firsttest');	// post 'what' to page formprocess.php
http.setEntity('  what  ');

http.setRequest('GET','pagetwo.php','regupdate');		// get info from pagetwo
http.setHeaderValue('Cache-Control','no-cache'); 		// set no-cache header
http.setReturn('mydivid','regupdate'); 					// set the place to return output to, this can be 'id' or functionname or false(default) to discard return

http.execute(); 										// execute both requests
http.removeRequest('firsttest'); 						// remove the request with ref: firsttest
http.execute(); 										// execute again with the one remaining request (regupdate)
http.execute(false); 									// execute again with the one remaining request and reset to a blank object when done.

thoughts: interval("http.execute()", 1000); update X every second..
notes: there's no limit to the amount of requests, you can run 5000 on an execute if you want..
*/

already read the doc's ;)
 
0
•••
Try this:

Code:
function init()
{
	if (typeof XMLHttpRequest == 'undefined')
	{
		objects = Array(
			'Microsoft.XMLHTTP',
			'MSXML2.XMLHTTP',
			'MSXML2.XMLHTTP.3.0 ',
			'MSXML2.XMLHTTP.4.0',
			'MSXML2.XMLHTTP.5.0'
		);

		for (i in objects)
		{
			try
			{
				return new ActiveXObject(objects[i]);
			}
			catch (e) {}
		}
	}
	else
	{
		return new XMLHttpRequest();
	}
}

function get(id)
{
	return document.getElementById(id);
}

function get_form(str, field)
{
	xmlhttp = init();
	xmlhttp.onreadystatechange =  function ()
	{
		if (xmlhttp.readyState == 4)
		{
			if (xmlhttp.status == 200)
			{
				get(field).innerHTML = xmlhttp.responseText;
			}
			else
			{
				get(field).innerHTML = 'There has been a problem';
			}
		}
	};
	xmlhttp.open("GET", "/admin/test.php?type="+str, true);
	xmlhttp.send(null);
}
untested
 
0
•••
reviewed the original code.. would appear that..
readystate should be readyState
responsetext should be responseText
firefox is a lot tighter (and rightly so) on these things; hope that helps; works on ff2 + 3 this end

additionally swap send(null) for send('') will keep it working in all browsers
 
1
•••
SecondVersion said:
Try this:

Code:
function init()
{
	if (typeof XMLHttpRequest == 'undefined')
	{
		objects = Array(
			'Microsoft.XMLHTTP',
			'MSXML2.XMLHTTP',
			'MSXML2.XMLHTTP.3.0 ',
			'MSXML2.XMLHTTP.4.0',
			'MSXML2.XMLHTTP.5.0'
		);

		for (i in objects)
		{
			try
			{
				return new ActiveXObject(objects[i]);
			}
			catch (e) {}
		}
	}
	else
	{
		return new XMLHttpRequest();
	}
}

function get(id)
{
	return document.getElementById(id);
}

function get_form(str, field)
{
	xmlhttp = init();
	xmlhttp.onreadystatechange =  function ()
	{
		if (xmlhttp.readyState == 4)
		{
			if (xmlhttp.status == 200)
			{
				get(field).innerHTML = xmlhttp.responseText;
			}
			else
			{
				get(field).innerHTML = 'There has been a problem';
			}
		}
	};
	xmlhttp.open("GET", "/admin/test.php?type="+str, true);
	xmlhttp.send(null);
}
untested

Sort of defeats what I am tryingto do tbh. Doing this every different script would need it's own function and its own callback.

Each script having its own function isnt much of an issue but I would prefer not replicting callbacks

blacknet said:
reviewed the original code.. would appear that..
readystate should be readyState
responsetext should be responseText
firefox is a lot tighter (and rightly so) on these things; hope that helps; works on ff2 + 3 this end

additionally swap send(null) for send('') will keep it working in all browsers


Ahh perfect that has actually resolved the issue.

re doing xmlhttp.onreadystatechange = callback(); every piece of text I have read on the matter states that instead ofassigning callback() as the callback function it simply assigns the result to xmlhttp.onreadystatechange. This makes sense as it is exactly the same as in PHP.

However matter is resolved. I thought it would be something simple but just was not sure where to start. Would be much easier if firefox actually gave the javascript errors.
 
0
•••
Peter said:
Would be much easier if firefox actually gave the javascript errors.

It Does :) "error console"
ctrl+shift+j [or] tools>error console
 
0
•••
Unstoppable Domains
Domain Recover
DomainEasy โ€” Zero Commission
  • The sidebar remains visible by scrolling at a speed relative to the pageโ€™s height.
Back