Jump to content

Looping a server connection?


bobleny

Recommended Posts

OK, I created a script that is confusing the hell into me!  >:(

 

fooy.php

<?php
echo "Fooy on you!<br />";
?>

 

foo.php

<html>
<head>
	<script type="text/javascript">
		<!--
			var GetServer
			function Connect()
			{
				try
				{
					// Firefox, Opera 8.0+, Safari
					GetServer = new XMLHttpRequest();
				}
				catch (e)
				{
					// Internet Explorer
					try
					{
						GetServer = new ActiveXObject("Msxml2.XMLHTTP");
					}
					catch (e)
					{
						try
						{
							GetServer = new ActiveXObject("Microsoft.XMLHTTP");
						}
						catch (e)
						{
							return false;
						}
					}
				}
			}

			function Foo()
			{
				var cnt1 = 0;
				var cnt2 = 0;
				for (var i = 1; i <= 5; i++)
				{
					document.getElementById("echo").innerHTML += i + "<br />";
					Connect();

					var site = "fooy.php";
					GetServer.open("GET",site,true);
					GetServer.send(null);

					cnt1++;

					GetServer.onreadystatechange=function()
					{
						cnt2++;
						if(GetServer.readyState == 4)
						{
							document.getElementById("echo").innerHTML += GetServer.responseText;
						}
					}
				}
				document.getElementById("cnt1").innerHTML += "Count 1: " + cnt1;
				document.getElementById("cnt2").innerHTML += "Count 2: " + cnt2;
			}
		-->
	</script>
</head>
<body>
	<div id="echo"></div>
	<div id="cnt1"></div>
	<div id="cnt2"></div>
	<input type='button' value='Foo It!' onclick="Foo()">
</body>
</html>

 

 

The output of the above script when the button is pressed is this:

1
2
3
4
5
Fooy on you!
Count 1: 5
Count 2: 0

 

 

I would like the output to look like this:

1
2
3
4
5
Fooy on you!
Fooy on you!
Fooy on you!
Fooy on you!
Fooy on you!
Count 1: 5
Count 2: 5

 

 

I don't get it! Shouldn't it connect to fooy.php 5 times??

 

Furthermore shouldn't cnt2 equal at least 1! I mean, if it echoed "Fooy on you!" once, then it had to of done cnt2++; at least once.... (I did check cnt2, it is the correct number... Some how...)

 

Any ideas, suggestions?

 

Thanks!

Link to comment
https://forums.phpfreaks.com/topic/79363-looping-a-server-connection/
Share on other sites

Your XMLHTTPRequest (XHR) Object Instance is a global. (GetServer)

Every time you call Connect() you reset this Object. What happens is the XHR is canceled and a new one made - depending on browser.

 

You need to create a new Instance for each XHR you make. Let each XHR complete, before reusing the Instance, or destroying it.

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.