473,804 Members | 2,460 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 onreadystatecha nge
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.p hp",true);
http.onreadysta techange = function () {
if (http.readyStat e == 4 && http.status == 200) {
// XML
XML_result = http.responseXM L;
docNode = XML_result.docu mentElement;
msg_count = docNode.getElem entsByTagName(' message').lengt h;
i = 0;
while(i < msg_count) {
messagesNode = docNode.getElem entsByTagName(' message')[i];
datetime =
messagesNode.ge tElementsByTagN ame('datetime')[0].firstChild.dat a;
from =
messagesNode.ge tElementsByTagN ame('from')[0].firstChild.dat a;
message =
messagesNode.ge tElementsByTagN ame('text')[0].firstChild.dat a;
FormatMessage(d atetime,from,me ssage);
i++;
}
}
}
http.send(null) ;
setTimeout(Refr eshChat,10000);
}

function FormatMessage(d atetime,from,me ssage) {
httpnew.open("G ET","formatmess age.php",true);
httpnew.onready statechange = function() {
if(httpnew.read yState == 4 && httpnew.status == 200) {
alert(httpnew.r eadyState);
formattedmessag e = httpnew.respons eText;
document.getEle mentById('chata rea').innerHTML = formattedmessag e;
}
else {
document.getEle mentById('chata rea').innerHTML = "Error!";
}
}
}
When I run the RefreshChat() function, everything runs fine up to...
httpnew.onready statechange = function() {
in the FormatMessage function, because the state never changes
(readyState is always 1).

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

May 5 '06 #1
6 7299
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 onreadystatecha nge
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(d atetime,from,me ssage)

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

I thought something like following was needed :

function getHTTPObject(t ype_mine) {
http_request = false;
if (window.XMLHttp Request) { // Mozilla, Safari,...
http_request = new XMLHttpRequest( );
if(http_request .overrideMimeTy pe) {
http_request.ov errideMimeType( type_mine);
}
}
else if (window.ActiveX Object) { // IE
try {
http_request = new ActiveXObject(" Msxml2.XMLHTTP" );
}
catch (e) {
try {
http_request = new ActiveXObject(" Microsoft.XMLHT TP");
}
catch (e) {}
}
}
return http_request;
}
function RefreshChat() {
http = getHTTPObject(' text/xml');
http.open("GET" ,"refreshchat.p hp",true);
I think
http.open would have to be after http.onreadysta techange
http.onreadysta techange = function () {
if (http.readyStat e == 4 && http.status == 200) {
// XML
XML_result = http.responseXM L;
docNode = XML_result.docu mentElement;
msg_count = docNode.getElem entsByTagName(' message').lengt h;
i = 0;
while(i < msg_count) {
messagesNode = docNode.getElem entsByTagName(' message')[i];
datetime =
messagesNode.ge tElementsByTagN ame('datetime')[0].firstChild.dat a;
from =
messagesNode.ge tElementsByTagN ame('from')[0].firstChild.dat a;
message =
messagesNode.ge tElementsByTagN ame('text')[0].firstChild.dat a;
FormatMessage(d atetime,from,me ssage);
i++;
}
}
}
http.send(null) ;
setTimeout(Refr eshChat,10000);
}

function FormatMessage(d atetime,from,me ssage) {
httpnew = getHTTPObject(' text/html');

/*
httpnew.open("G ET","formatmess age.php",true);
*/
httpnew.onready statechange = function() {
if(httpnew.read yState == 4 && httpnew.status == 200) {
alert(httpnew.r eadyState);
formattedmessag e = httpnew.respons eText;
document.getEle mentById('chata rea').innerHTML = formattedmessag e;
}
else {
document.getEle mentById('chata rea').innerHTML = "Error!";
}
}
httpnew.open("G ET","formatmess age.php",true);
}
When I run the RefreshChat() function, everything runs fine up to...
httpnew.onready statechange = function() {
in the FormatMessage function, because the state never changes
(readyState is always 1).

Both the php pages (refreshchat.ph p) 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 onreadystatecha nge. onreadystatecha nge 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.htm l
<html>
<head>
<title>Ajax at work</title>

<script language = "javascript ">

function ProgressBar() {
var XMLHttpRequestO bject = false;
if (window.XMLHttp Request) { XMLHttpRequestO bject = new
XMLHttpRequest( ); }
else if (window.ActiveX Object) { XMLHttpRequestO bject = new
ActiveXObject(" Microsoft.XMLHT TP"); }
if(XMLHttpReque stObject) {
var obj = document.getEle mentById('progr ess');
currentpercent = obj.style.width ;
XMLHttpRequestO bject.open("GET ", "progressbar.ph p?last=" +
currentpercent + "", true);
XMLHttpRequestO bject.onreadyst atechange = function() {
if (XMLHttpRequest Object.readySta te == 4 &&
XMLHttpRequestO bject.status == 200) {
obj.style.width = XMLHttpRequestO bject.responseT ext + '%';
document.getEle mentById('waiti ng').innerHTML = '';
if(XMLHttpReque stObject.respon seText < 100) {
ProgressBar();
}
else { document.getEle mentById('waiti ng').innerHTML =
'<b>DONE!</b>'; }
}
else { document.getEle mentById('waiti ng').innerHTML = 'Loading...';
}
}
XMLHttpRequestO bject.send(null );
}
}

function ProgressBar2() {
var XMLHttpRequestO bject = false;
if (window.XMLHttp Request) { XMLHttpRequestO bject = new
XMLHttpRequest( ); }
else if (window.ActiveX Object) { XMLHttpRequestO bject = new
ActiveXObject(" Microsoft.XMLHT TP"); }
if(XMLHttpReque stObject) {
XMLHttpRequestO bject.open("GET ", "progressbar2.p hp", true);
XMLHttpRequestO bject.onreadyst atechange = function() {
if (XMLHttpRequest Object.readySta te == 4 &&
XMLHttpRequestO bject.status == 200) {
document.getEle mentById('progr ess_2').innerHT ML = 'DONE';
}
else { document.getEle mentById('progr ess_2').style.v isibility =
'visible'; }
}
XMLHttpRequestO bject.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:20 0px; height:15px; background-color:#FFCCFF;
border:1px solid #000000;" onClick="Progre ssBar();">
<div id="progress" style="height:1 5px; width:0%;
background-color:#FF0000"> </div>
</div>

<div id="waiting">Cl ick 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="Progre ssBar2();">Star t</a>
<br>
<div id="progress_2 " style="visibili ty:hidden;">
<img src="progressba r.gif"><br>
Loading...
</div>

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

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

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

progressbar.htm l
.... is not Valid markup: <URL:http://validator.w3.or g/>
[...]
function ProgressBar() {
var XMLHttpRequestO bject = false;
Do not use tabs to indent your code (at least not when posting);
use multiples of 2 or 4 spaces.
if (window.XMLHttp Request) { XMLHttpRequestO bject = new
XMLHttpRequest( ); }
else if (window.ActiveX Object) { XMLHttpRequestO bject = new
ActiveXObject(" Microsoft.XMLHT TP"); }
[...]
Should be at least

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

var _global = this;

function progressBar()
{
var xmlhttp = null;

if (isMethod(_glob al.XMLHttpReque st))
{
xmlhttp = new XMLHttpRequest( );
}
else if (isMethod(_glob al.ActiveXObjec t)
{
xmlhttp = new ActiveXObject(" Microsoft.XMLHT TP");
}

if (xmlhttp)
{
var obj;
if (isMethod(docum ent.getElementB yId)
&& (obj = document.getEle mentById('progr ess')))
{
var currentPercent = getStylePropert y(obj, 'width');
xmlhttp.open("G ET", "progressbar.ph p?last=" + currentPercent, true);

xmlhttp.onready statechange = function()
{
var waiting = document.getEle mentById('waiti ng');
if (xmlhttp.readyS tate == 4 && xmlhttp.status == 200)
{
obj.style.width = xmlhttp.respons eText + '%';
if (waiting)
{
waiting.innerHT ML = '';
if (xmlhttp.respon seText < 100)
{
progressBar();
}
else
{
waiting.innerHT ML = '<b>DONE!<\/b>';
}
}
}
else
{
waiting.innerHT ML = 'Loading...';
}
}
xmlhttp.send(nu ll);
}
}
}
function ProgressBar2() {
Have you ever considered making your functions reusable by passing
arguments?
[...]
<div style="width:20 0px; height:15px; background-color:#FFCCFF;
border:1px solid #000000;" onClick="Progre ssBar();">
<div id="progress" style="height:1 5px; 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">Cl ick 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="Progre ssBar2();">Star t</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.ph p
<?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.XMLHttp Request) { XMLHttpRequestO bject = new
XMLHttpRequest( ); }
else if (window.ActiveX Object) { XMLHttpRequestO bject = new
ActiveXObject(" Microsoft.XMLHT TP"); }
[...]


Should be at least
[...]
if (xmlhttp)
{
var obj;
if (isMethod(docum ent.getElementB yId)
&& (obj = document.getEle mentById('progr ess')))
{
var currentPercent = getStylePropert y(obj, 'width');


Where getStylePropert y() 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
4343
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; myform.submit(); The above code only submit form to url_of_server1. The second submit is ignored. Is there any trick to make it works? For example is it
7
2542
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 demo based on this article/code "Handling Multiple XMLHTTPRequest Objects" at http://www.drakware.com/articles/multijax.php, which does make mutliple requests, but never two seem to happen at the same time.
1
8225
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 a query is performed and the results are dynamically entered into a multiple select box below the textfield without reloading the page, or affecting other form elements. If no data is found then an error message is displayed in place of the...
17
11887
by: Arjen | last post by:
Hi, I want to reload 2 divs at one click. Ive tried: <a href = "javascript:void(0);" onclick="show('ajaxrequest.php?action=removefield','div1');show('ajaxrequest.php?action=reloaddiv2','div2')">verwijderen</a> While both seperate actions work they dont when I put them together. Anyone know how to fix this ? My ajax.js with funcition show
4
4667
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 have been successfully registered.</div>"); within 1.5 seconds. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta...
7
5454
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 possible to do in a straightforward fashion, given the normally asynchronous method of XMLHttp. The (untested, pseudo) code below gives a little idea of what the goal is, but I'm not really sure how to program it elegantly. One thought I had is...
1
2022
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 the contents from a server side script as AJAX generally does and process it using that function. This far Im quite pleased with it, however, I really want something that will allow me to perform multiple AJAX calls from the same script. I...
9
4509
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 solution would be fake multiple file upload. It's takes only address of directorys and after choosing few address, you could push send button and PHP would do the rest.
0
9571
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10561
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10318
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10302
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10069
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9132
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7608
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
5505
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4277
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

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.