Go Back   CodingForums.com > :: Client side development > JavaScript programming > Ajax and Design

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 03-08-2009, 04:54 AM   PM User | #1
onmoon
New Coder

 
Join Date: Mar 2007
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
onmoon is an unknown quantity at this point
XMLHttpRequest not working in Loop

Try to load details from sever side based on the provided prarams which are store in an array. Thus, there will be a loop, sending different request with different array element value. and I will use the return values (req.responseText) to replace some parts of the page.

The problem is that only the last request will be given the correct value. I tried to add "alert('');" to find out the problem, interesting thing is, if I close the alert window a little big slowly, all requests will be returned with correct values. However, if close them very quickly, only the last request working.

I thought it might be the reason that XMLHttpRequest need more time to process, and try to add setTimeout, not lucky, the same.

Below are main processing codes, please advise, thanks!

// loadParams has been defined by the array before it is sent here

//alert(loadParams );
if (window.XMLHttpRequest) {
req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState==4)
if (req.status==200)
//do innerHTML replace
}
req.open("GET", loadParams, true);
req.setRequestHeader("Content-Type","text/html;charset=utf-8");
req.send(null);
} else if (window.ActiveXObject) {
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = function(){
if (req.readyState==4)
if (req.status==200)
//do innerHTML replace
}
req.open("GET", loadParams, true);
req.setRequestHeader("Content-Type","text/html;charset=utf-8");
req.send();
}
}
onmoon is offline   Reply With Quote
Old 03-08-2009, 06:18 AM   PM User | #2
tomws
Senior Coder

 
tomws's Avatar
 
Join Date: Nov 2007
Location: Arkansas
Posts: 2,644
Thanks: 29
Thanked 330 Times in 326 Posts
tomws will become famous soon enoughtomws will become famous soon enough
You're correct - it does need more time to process. That's the reason the last result is the only one that seems to provide the expected result. When the script hits the xmlhttp request, it continues processing on past it while the request is "out there" doing it's work. So, what's happening is that the subsequent requests are killing the previous requests.

One solution is to restructure your code to remove the loop. Another solution is to use a queue. I can't find the link for the one I've used, but you might try Googling for ajax request queue.
__________________
Are you a Help Vampire?
tomws is offline   Reply With Quote
Old 03-08-2009, 09:28 AM   PM User | #3
onmoon
New Coder

 
Join Date: Mar 2007
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
onmoon is an unknown quantity at this point
thanks! google now.
onmoon is offline   Reply With Quote
Old 03-08-2009, 09:29 AM   PM User | #4
itsallkizza
Senior Coder

 
Join Date: Oct 2008
Location: Long Beach
Posts: 1,196
Thanks: 36
Thanked 164 Times in 164 Posts
itsallkizza will become famous soon enough
Something like this perhaps?

example: http://buildyourownbagel.com/test/test2.html

test2.html:
Code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Example</title>
<style type="text/css">
</style>
<script type="text/javascript">
// <![CDATA[

function XMLHTTP_Util()
	{
	this.sendRequest = function(url,method,params,async,callback,callbackargs)
		{
		method = method ? method.toUpperCase() : "GET";
		if (typeof(callback) == "string") callback = new Function(callback);
		callback = callback || function(){};
		params = params ? params.join("&") : "";
		if (method == "GET" && params) url += "?"+params;
		var req = this.createXMLHTTPObject();
		if (!req) callback.call(this,false,callbackargs);
		req.ref = this;
		req.open(method,url,async);
		req.setRequestHeader('User-Agent','XMLHTTP/1.0');
		if (method == "POST")
			{
			req.setRequestHeader("Content-type","application/x-www-form-urlencoded");
			req.setRequestHeader("Content-length",params.length);
			req.setRequestHeader("Connection","close");
			}
		req.onreadystatechange = function()
			{
			if (this.readyState != 4) return;
			if (this.status != 200 && this.status != 304)
				{
				//alert("HTTP error " + req.status);
				callback.call(this.ref,false,callbackargs);
				}
			else
				{
				callback.call(this.ref,req,callbackargs);
				}
			}
		if (req.readyState == 4) return;
		req.send(method=="GET"?null:params);
		}
	this.createXMLHTTPObject = function()
		{
		var xmlhttp = false;
		for (var i=0;i<this.XMLHttpFactories.length;i++)
			{
			try
				{
				xmlhttp = this.XMLHttpFactories[i]();
				}
			catch(e)
				{
				continue;
				}
			break;
			}
		return xmlhttp;
		}
	this.XMLHttpFactories = [
	function() {return new XMLHttpRequest()},
	function() {return new ActiveXObject("Msxml2.XMLHTTP")},
	function() {return new ActiveXObject("Msxml3.XMLHTTP")},
	function() {return new ActiveXObject("Microsoft.XMLHTTP")}
	];
	}
var xhu = new XMLHTTP_Util();

var prev_params = [10,34,25,16];

function displayRate(req)
	{
	document.getElementById("output").innerHTML += req.responseText+"<br />";
	}

function startSendingRequests()
	{
	for (var i=0;i<prev_params.length;i++)
		{
		xhu.sendRequest("get_rate.php","get",["rate_input="+prev_params[i]],true,displayRate);
		}
	}

window.onload = function()
	{
	startSendingRequests();
	}

// ]]>
</script>
</head>
<body>

<div id="output"></div>

</body>
</html>
get_rate.php:
Code:
<?php
$i = (int)$_GET["rate_input"];
echo($i*0.26);
?>
__________________
Feel free to e-mail me if I forget to respond ;)
ohsosexybrit@gmail.com
itsallkizza is offline   Reply With Quote
Old 03-08-2009, 02:54 PM   PM User | #5
onmoon
New Coder

 
Join Date: Mar 2007
Posts: 25
Thanks: 0
Thanked 0 Times in 0 Posts
onmoon is an unknown quantity at this point
Solved! Ajax request queue, very helpful.
onmoon is offline   Reply With Quote
Old 03-08-2009, 05:03 PM   PM User | #6
itsallkizza
Senior Coder

 
Join Date: Oct 2008
Location: Long Beach
Posts: 1,196
Thanks: 36
Thanked 164 Times in 164 Posts
itsallkizza will become famous soon enough
Queueing is slower than sending the requests asynchronously by either
a) attacking a reference to the handler and calling it using function.call(response), or
b) attaching an id to the request and having it send the id back with the response

Both methods allow you to send your requests simultaneously and receive them asap while still able to track which callbacks are being called by which request.
__________________
Feel free to e-mail me if I forget to respond ;)
ohsosexybrit@gmail.com
itsallkizza is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 09:11 PM.


Advertisement
Log in to turn off these ads.