Multiple XMLHTTPRequest?

N

Nathan

Can I run two XMLHTTPRequest objects at the same time? Im able to get
one to work without problems.

If I put a call to a function inside the first ones onreadystatechange
function, the 2nd ones readyState is always set to 1 (loading). Ive
tried using the same XMLHTTPRequest object, and making a 2nd
XMLHTTPRequest object with the same results. Heres my code thats giving
me problems...

function RefreshChat() {
http.open("GET","refreshchat.php",true);
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
// XML
XML_result = http.responseXML;
docNode = XML_result.documentElement;
msg_count = docNode.getElementsByTagName('message').length;
i = 0;
while(i < msg_count) {
messagesNode = docNode.getElementsByTagName('message');
datetime =
messagesNode.getElementsByTagName('datetime')[0].firstChild.data;
from =
messagesNode.getElementsByTagName('from')[0].firstChild.data;
message =
messagesNode.getElementsByTagName('text')[0].firstChild.data;
FormatMessage(datetime,from,message);
i++;
}
}
}
http.send(null);
setTimeout(RefreshChat,10000);
}

function FormatMessage(datetime,from,message) {
httpnew.open("GET","formatmessage.php",true);
httpnew.onreadystatechange = function() {
if(httpnew.readyState == 4 && httpnew.status == 200) {
alert(httpnew.readyState);
formattedmessage = httpnew.responseText;
document.getElementById('chatarea').innerHTML = formattedmessage;
}
else {
document.getElementById('chatarea').innerHTML = "Error!";
}
}
}


When I run the RefreshChat() function, everything runs fine up to...
httpnew.onreadystatechange = function() {
in the FormatMessage function, because the state never changes
(readyState is always 1).

Both the php pages (refreshchat.php) and (formatmessage.php) exist and
dont timeout or have errors.
 
A

ASM

Nathan a écrit :
Can I run two XMLHTTPRequest objects at the same time? Im able to get
one to work without problems.

If I put a call to a function inside the first ones onreadystatechange
function, the 2nd ones readyState is always set to 1 (loading). Ive
tried using the same XMLHTTPRequest object, and making a 2nd
XMLHTTPRequest object with the same results. Heres my code thats giving
me problems...

What I don't understand is where you declare
'http' in RefreshChat()
and
'httpnew' in FormatMessage(datetime,from,message)

first in typeMine text/xml
second in typeMine text/html

I thought something like following was needed :

function getHTTPObject(type_mine) {
http_request = false;
if (window.XMLHttpRequest) { // Mozilla, Safari,...
http_request = new XMLHttpRequest();
if(http_request.overrideMimeType) {
http_request.overrideMimeType(type_mine);
}
}
else if (window.ActiveXObject) { // IE
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
return http_request;
}
function RefreshChat() {

http = getHTTPObject('text/xml');
http.open("GET","refreshchat.php",true);

I think
http.open would have to be after http.onreadystatechange
http.onreadystatechange = function () {
if (http.readyState == 4 && http.status == 200) {
// XML
XML_result = http.responseXML;
docNode = XML_result.documentElement;
msg_count = docNode.getElementsByTagName('message').length;
i = 0;
while(i < msg_count) {
messagesNode = docNode.getElementsByTagName('message');
datetime =
messagesNode.getElementsByTagName('datetime')[0].firstChild.data;
from =
messagesNode.getElementsByTagName('from')[0].firstChild.data;
message =
messagesNode.getElementsByTagName('text')[0].firstChild.data;
FormatMessage(datetime,from,message);
i++;
}
}
}
http.send(null);
setTimeout(RefreshChat,10000);
}

function FormatMessage(datetime,from,message) {


httpnew = getHTTPObject('text/html');

/*
 
N

Nathan

I have a getHTTPObject function, I just didnt paste it here. And the
open has to be before the onreadystatechange. onreadystatechange is the
status of the open call. I found in Ajax for dummies chapter 4 covers
overloading and handling multiple concurrent requests... so Im reading
that now. Looks as though you must created a 2nd instance of the object
inside the function, but still working on getting it to work.
 
N

Nathan

Well I finally got it to work... here it is for those interested...

progressbar.html
<html>
<head>
<title>Ajax at work</title>

<script language = "javascript">

function ProgressBar() {
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) { XMLHttpRequestObject = new
XMLHttpRequest(); }
else if (window.ActiveXObject) { XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP"); }
if(XMLHttpRequestObject) {
var obj = document.getElementById('progress');
currentpercent = obj.style.width;
XMLHttpRequestObject.open("GET", "progressbar.php?last=" +
currentpercent + "", true);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
obj.style.width = XMLHttpRequestObject.responseText + '%';
document.getElementById('waiting').innerHTML = '';
if(XMLHttpRequestObject.responseText < 100) {
ProgressBar();
}
else { document.getElementById('waiting').innerHTML =
'<b>DONE!</b>'; }
}
else { document.getElementById('waiting').innerHTML = 'Loading...';
}
}
XMLHttpRequestObject.send(null);
}
}

function ProgressBar2() {
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) { XMLHttpRequestObject = new
XMLHttpRequest(); }
else if (window.ActiveXObject) { XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP"); }
if(XMLHttpRequestObject) {
XMLHttpRequestObject.open("GET", "progressbar2.php", true);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 &&
XMLHttpRequestObject.status == 200) {
document.getElementById('progress_2').innerHTML = 'DONE';
}
else { document.getElementById('progress_2').style.visibility =
'visible'; }
}
XMLHttpRequestObject.send(null);
}
}

</script>
</head>

<body>

<b>% Progress bar</b><br>
Good for file downloads or big database compares/querys where you can
do it in steps. Will not work things you<br>
cannot do in steps (such as loading a webpage) because it will jump
from 0% to 100%.<br>
<br>
<div style="width:200px; height:15px; background-color:#FFCCFF;
border:1px solid #000000;" onClick="ProgressBar();">
<div id="progress" style="height:15px; width:0%;
background-color:#FF0000"></div>
</div>

<div id="waiting">Click progress bar to start</div>
<br>
<br>
<b>General progress bar</b><br>
Good for things you cannot step through, such as loading a webpage or a
picture.<br>
<a href="#" onClick="ProgressBar2();">Start</a>
<br>
<div id="progress_2" style="visibility:hidden;">
<img src="progressbar.gif"><br>
Loading...
</div>

</body>
</html>


progressbar.php
<?php
$progress = ($_GET['last']+rand(0,5));
if($progress >= 100) { $progress = 100; }
print($progress);
?>

progressbar2.php
<?php
sleep(5);
?>
 
T

Thomas 'PointedEars' Lahn

Nathan said:
Can I run two XMLHTTPRequest objects at the same time?

Of course. However, you may not be able to send one request per
XMLHTTPRequest object at the same time. Limits on allowed HTTP
connections may force the second request (whichever request is
made first [that is not which corresponding object is created
first] would become the first one) into a queue. Internet
Explorer is known to be especially restrictive on the number
of HTTP connections; for example Gecko-based UAs allow you to
increase that value through a user preference.


PointedEars
 
T

Thomas 'PointedEars' Lahn

Nathan said:
Well I finally got it to work... here it is for those interested...

progressbar.html

.... is not Valid markup: said:
[...]
function ProgressBar() {
var XMLHttpRequestObject = false;

Do not use tabs to indent your code (at least not when posting);
use multiples of 2 or 4 spaces.
if (window.XMLHttpRequest) { XMLHttpRequestObject = new
XMLHttpRequest(); }
else if (window.ActiveXObject) { XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP"); }
[...]

Should be at least

function isMethod(a)
{
return a && /^\s*(function|object)\s*$/.test(typeof a);
}

var _global = this;

function progressBar()
{
var xmlhttp = null;

if (isMethod(_global.XMLHttpRequest))
{
xmlhttp = new XMLHttpRequest();
}
else if (isMethod(_global.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}

if (xmlhttp)
{
var obj;
if (isMethod(document.getElementById)
&& (obj = document.getElementById('progress')))
{
var currentPercent = getStyleProperty(obj, 'width');
xmlhttp.open("GET", "progressbar.php?last=" + currentPercent, true);

xmlhttp.onreadystatechange = function()
{
var waiting = document.getElementById('waiting');
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
obj.style.width = xmlhttp.responseText + '%';
if (waiting)
{
waiting.innerHTML = '';
if (xmlhttp.responseText < 100)
{
progressBar();
}
else
{
waiting.innerHTML = '<b>DONE!<\/b>';
}
}
}
else
{
waiting.innerHTML = 'Loading...';
}
}
xmlhttp.send(null);
}
}
}
function ProgressBar2() {

Have you ever considered making your functions reusable by passing
arguments?
[...]
<div style="width:200px; height:15px; background-color:#FFCCFF;
border:1px solid #000000;" onClick="ProgressBar();">
<div id="progress" style="height:15px; width:0%;
background-color:#FF0000"></div>
</div>

Have you ever considered using `style' or `link' elements instead of
`style' attributes to make source code easier legible and maintainable?
<div id="waiting">Click progress bar to start</div>
<br>
<br>

Do not use the `br' element for margins; use CSS.
<b>General progress bar</b><br>

Do not use the `b' element for headings; use `hX' elements (X='1'..'6').
[...]
<a href="#" onClick="ProgressBar2();">Start</a>

Do not use a[href] elements for script-only features (and if you do, cancel
the click event!); use (formatted) buttons.
[...]
progressbar.php
<?php
$progress = ($_GET['last']+rand(0,5));

AFAIK there is no point to the outer parens. Is there a point to adding
rand(0, 5) here at all? (I could accept rand(1, 5) for test purposes;
the bounds are included.)
if($progress >= 100) { $progress = 100; }
print($progress);

Note that `print' is a language feature, not a function.

Pretty printing: zero.

<?php

$progress = $_GET['last'] + rand(0, 5);
if ($progress >= 100) $progress = 100;
print $progress;

?>
progressbar2.php
<?php
sleep(5);
?>

<?php sleep(5); ?>


PointedEars
 
T

Thomas 'PointedEars' Lahn

Thomas said:
Nathan said:
if (window.XMLHttpRequest) { XMLHttpRequestObject = new
XMLHttpRequest(); }
else if (window.ActiveXObject) { XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP"); }
[...]

Should be at least
[...]
if (xmlhttp)
{
var obj;
if (isMethod(document.getElementById)
&& (obj = document.getElementById('progress')))
{
var currentPercent = getStyleProperty(obj, 'width');

Where getStyleProperty() is not a built-in, but defined in my dhtml.js[1]
(and accidentally used here, while I was running on optimization).
Since I am mentioning that, other parts of the code could be made
more "bullet-proof" as well using other methods from that library
and my other libraries (such as isMethod() from types.js as included
here) as well. See the comments in the source code for details.


PointedEars
___________
[1] <URL:http://pointedears.de/scripts/dhtml.js>
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,968
Messages
2,570,153
Members
46,701
Latest member
XavierQ83

Latest Threads

Top