Javascript in Firefox cannot access DOM elements loaded via Ajax

Hi,

I’m having a bit of an issue with Javascript in Firefox (This is not a problem in IE or Chrome and works fine in those).

I have a small function that loops form elements and returns a formatted string for use with AJAX Post requests:

function parseForm(form) {
	var loadString="";
	var x=document.getElementById(form);
	for (var i=0;i<x.length-1;i++)
	{
		if (x.elements[i].value) {
			if (x.elements[i].name=="limit") {
				if (x.elements[i].value>5000) {
					js_die("Record limit cannot be greater than 5000");
				}
			}
			loadString=loadString+x.elements[i].name+"="+x.elements[i].value+"&";
		}
	}
	return loadString;
}

This code works as expected on forms that were in the initial page load (DOM), but in Firefox, getElementById() picks up nothing if the form was not in the original page (ie, loaded with Ajax).
Is this a restriction in Firefox? A feature yet to be implemented? A bug?
I’ve googled, but all I find is jquery stuff which I’m not using.

Hope someone can help me.
Thanks
David

Ajax requests occur asynchronously, so after performing an ajax request, you cannot expect to run commands that do anything with that content.

An example of what not to do:


$('#content').load('domain.com/testform.html');
var loadString = parseForm('register');

Instead, you need to use a callback so that after the ajax content has been successfully received, that callback will then be run.

For example:


$('#content').load('domain.com/testform.html', function () {
    var loadString = parseForm('register');
    ...
});

For when using vanilla javascript, you can use code from the Bulletproof Ajax book which provides [url=“http://bulletproofajax.com/code/”]code and examples that provide useful demonstrations of how things are done.

For example:


function getHTTPObject() {
    ...
}
function grabFile(file) {
  var request = getHTTPObject();
  if (request) {
    request.onreadystatechange = function() {
      displayResponse(request);
    };
    request.open("GET", file, true);
    request.send(null);
  }
}

function displayResponse(request) {
  if (request.readyState == 4) {
    if (request.status == 200 || request.status == 304) {
      // do stuff with the requested data here
    }
  }
}