473,394 Members | 1,714 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,394 software developers and data experts.

Multiple XMLHTTPRequest?

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')[i];
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.

May 5 '06 #1
6 7229
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')[i];
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');

/*
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!";
}
}
httpnew.open("GET","formatmessage.php",true);
}
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.

--
Stephane Moriaux et son [moins] vieux Mac
May 6 '06 #2
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.

May 8 '06 #3
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.visibi lity =
'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);
?>

May 10 '06 #4
Nathan wrote:
Well I finally got it to work... here it is for those interested...

progressbar.html
.... is not Valid markup: <URL:http://validator.w3.org/>
[...]
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
--
But he had not that supreme gift of the artist, the knowledge of
when to stop.
-- Sherlock Holmes in Sir Arthur Conan Doyle's
"The Adventure of the Norwood Builder"
May 17 '06 #5
Thomas 'PointedEars' Lahn wrote:
Nathan wrote:
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>
--
Bill Gates isn't the devil -- Satan made sure hell
_worked_ before he opened it to the damned ...
May 17 '06 #6
Nathan wrote:
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
--
Homer: I have changed the world. Now I know how it feels to be God!
Marge: Do you want turkey sausage or ham?
Homer: Thou shalt send me *two*, one of each kind.
(Santa's Little Helper [dog] and Snowball [cat] run away :))
May 17 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
by: ningjun.wang | last post by:
How can I submit a form to multiple web sites when user click the submit button? Something like the following: myform.action = url_of_server1; myform.submit(); myform.action = url_of_server2;...
7
by: blueapricot416 | last post by:
Hello helpful computer people! I can't seem to get more than one request to fire simultaneously... and I have read there should be at least 2 possible (in IE) and more in Firefox. I made a...
1
by: trpost | last post by:
How can I accomplish the following using AJAX / PHP: I have a form with a text field and a search button next to the text field. When I type something in the text field and hit the search button...
17
by: Arjen | last post by:
Hi, I want to reload 2 divs at one click. Ive tried: <a href = "javascript:void(0);"...
4
by: sufian | last post by:
Below is the field where user enters his/her email address and the AJAX post request is sent to the server and the user sees the message: echo("<div id=\"message\" class=\"success\">Thank you! You...
7
by: Brent | last post by:
I'm trying to figure out how to iterate over an array that would send a series of XMLHttp requests. I'd like to have each request finish before the next one begins, but I believe that this is not...
1
by: bizt | last post by:
Hi, I am having my first real attempt at an ajax class as so far Ive managed to build one that, once instatiated, will allow me to define which function it will call on completion then retrieves...
9
by: torso | last post by:
Hi Does someone know a good tutorial for multiple file upload with xmlHttpRequest. I am trying to do directory upload. So I could choose directorys and upload those to the server. Another...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.