Jump to content

Multiple Ajax requests...


DaveEverFade

Recommended Posts

I've thought I had the answer to this but turns out I didn't:

 

Does anyone know how to have mulitple Ajax requests running? For example having one request getting something from one page and another getting something from a different page at the same time (using the same javascript function)?

 

At the moment I have it so that when a user requests something, the window.status changes to "Loading" so if they request something when it's in that state it simply does nothing, now I'd like to accomodate the multiple request...

 

Any ideas??

Dave

Link to comment
Share on other sites

Ok, so here's the ajax file I've built up (seems to lose all the tabbed formatting on here...). All the Ajax requests go through the Ajax() function...

 

 

function Ajax(GetPage, Params, Div, Type, Secondary)
<!--
{
document.body.style.cursor = 'auto';
if(window.status=="Loading")
{
//Perform secondary request
}else
{

if (Params!="")
{

	var str=null;
	if(Params.indexOf("=")==-1)
		{
		str=eval(Params+"();");
		}else
		{
		str=Params;
		}	
	//alert("We're debugging, please ignore this \n\n Get Page="+GetPage+"\n Params="+Params+"\nDiv="+Div)
}

var url=GetPage+".php?"
url+=str
url+="&id="+Math.random() //Random string after the url to avoid caching on newer machines

	request=GetXmlHttpObject();
	if(request==null)
		{
		alert("Your browser will not run AJAX requests")
		return
		}
	request.onreadystatechange=function(){stateChanged(Div)}
	if(Type=='post')
	{
		request.open('POST', GetPage+'.php', true);
      		request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      		request.setRequestHeader("Content-length", str.length);
      		request.setRequestHeader("Connection", "close");
  		request.send(str);
	}else
	{
		request.open("GET",url,true)
		request.send(null)
	}
}
}

function stateChanged(Div) 
{ 
if(request.readyState<4)
{
window.status="Loading";
document.body.style.cursor = 'wait';
}
if (request.readyState==4 || request.readyState=="complete")
{ 
document.getElementById(Div).innerHTML=request.responseText
window.status="Done";
document.body.style.cursor = 'auto';
} 
} 

function GetXmlHttpObject()
{ 
var objXMLHttp=null
if (window.XMLHttpRequest)
{
objXMLHttp=new XMLHttpRequest()
}
else if (window.ActiveXObject)
{
objXMLHttp=new ActiveXObject("Microsoft.XMLHTTP")
}
return objXMLHttp
}

Link to comment
Share on other sites

Doing request.open("GET",url,true) already implies that it is an asynchronous request. Asynchronous means the client javascript doesn't wait for a response to continue code execution. So you can just do another request right after it.

 

Maybe I don't understand the question, but I don't see any problems.

Link to comment
Share on other sites

Well, that is just a matter of having your implementation of .onreadystatechange (stateChanged) work with both requests. I.e. there has to be some metadata or a distinct property in the response that tells the function how to act.

Link to comment
Share on other sites

Well, using JSON you can probably make this a little easier, but for a cut-and-paste example:

 

function responseHandler() { 
if(http.readyState == 4 && http.status == 200) { 
	var response = http.responseXML;
	if(response) {
		var updates = response.getElementsByTagName('update');
		for(i=0; i<updates.length; i++)	{
			if(updates.item(i).textContent == null) {
				var html = updates.item(i).firstChild.nodeValue;
				if(!html) {
					return;
				}
			}
				else {
					var html = updates.item(i).textContent;
			}
			document.getElementById(updates.item(i).getAttribute('xml:id')+'container').innerHTML = html;
		}
	} 
} 
}

 

<?php
//Generate the contents of $updates here

header('Content-Type: text/xml');
header('Cache-Control: max-age=0, must-revalidate'); //No caching of ajax content right now 
echo '<?xml version="1.0" encoding="utf-8"?>';
echo '<response>';
foreach($updates as $id=>$content) {
echo '<update xml:id="'.$id.'">
		<![CDATA['.$content.']]>
	</update>';
}
echo '</response>';
?>

 

Note that this assumes that the id of update nodes corresponds with the target's id (+'container'). The order in which the responses are  gotten is irrelevant, all that matters is the update. If you need responses to be handled in a set order, i.e. don't process one update before the other has completed, store a response which is 'too early' (for example in a global variable). To differentiate between responses you can add a xml:id to the root node.

Link to comment
Share on other sites

Simple JSON response handler:

function responseHandler() { 
if(http.readyState == 4 && http.status == 200) { 
            response = eval("(" + http.responseText + ")");
            document.getElementById(response.target).innerHTML = response.html;
    }
};

 

Encoding JSON:

 

echo json_encode(array('target'=>'someId', 'html'=>'<p>Sometext</p>'));

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.