I'm an amateur web developer trying to move toward more professional coding practices, and I'm making my first site that makes extensive use of ajax. I've used the xmlHttpRequest object on a few occasions, for which simply creating functions as I needed them were adequate. But the site I am building now will require dozens or more of asynchronous requests, and each will require different instructions on how to process the returned data. I have been beating my head against the wall trying to figure out how to model this. This is what I have so far:

//I want to use this function to generate all my xhr requests
function xhrInit(url, method) {
	var data=new xhrFactory(url, method);

//so this creates the requests
function xhrFactory(url, method) {

/*and this sends the request; so far so good, I can use a basic function to get any data I want sent to any php page I want */
xhrFactory.prototype.xhrRequest= function() {
		var response='';
		var hfunc='xhrHandler';
		xhr_object=new XMLHttpRequest();
		xhr_object.open(this.method, this.url, 'true');
		xhr_object.onreadystatechange = xhrHandler;//do i need a way to change the handler dynamically?

//but this is where I get stuck
function xhrHandler () {
		var data=xhr_object.responseText;
		if (xhr_object.readyState==4) {
			if ((xhr_object.status >= 200 && xhr_object.status < 300) || xhr_object.status == 304) { 
/*or do I need a way to pass the response text to another function for processing? For this 'factory' to work I need an easy way to process the response data differentially */		}


As I understand it, the handler is called after the xhrRequest has completed, which means I cannot simply return the response text. I've tried using a variable in place of xhrHandler to see if I could get the function to call different handlers but it just treats the name of the handler as a string.

What I really need is a way to pass the response data to different processing functions, depending on the originating document. I have tried dozens of things (some of which I knew were absurd at the time) and can't figure out a way to do this. I would be incredibly grateful to have this puzzle solved!!!

*whoops, please ignore the variabls 'hfunc' and 'response' on lines 15&16, they are left-overs from previous failed solution attempts!

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.