Home     |     .Net Programming    |     cSharp Home    |     Sql Server Home    |     Javascript / Client Side Development     |     Ajax Programming

Ruby on Rails Development     |     Perl Programming     |     C Programming Language     |     C++ Programming     |     IT Jobs

Python Programming Language     |     Laptop Suggestions?    |     TCL Scripting     |     Fortran Programming     |     Scheme Programming Language


 
 
Cervo Technologies
The Right Source to Outsource

MS Dynamics CRM 3.0

Javascript / Client Side Development

Multiple ajax calls at once


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('ajaxreques t.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

var xmlHttp
var mydiv
function show(str,div)
{
        mydiv=div;

        if (str.length==0)
        {
                document.getElementById(mydiv).innerHTML=""
                return
        }
        xmlHttp=GetXmlHttpObject()
        if (xmlHttp==null)
        {
                alert ("Browser does not support HTTP Request")
                return
        }
        var url=""
        url=url+str
        url=url+"&rnd="+Math.random()
        xmlHttp.onreadystatechange=stateChanged()
        xmlHttp.open("GET",url,true)
        xmlHttp.send(null)

}

function stateChanged()
{
        if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
        {
                document.getElementById('loading').innerHTML="";
                document.getElementById(mydiv).innerHTML=xmlHttp.responseText

        }
        else
        {
                document.getElementById('loading').innerHTML="<h1>Loading ....
</h1><img src = '/fw/images/loading.gif'>";
        }

}

function GetXmlHttpObject()
{
        var xmlHttp=null;
        try
        {
                // Firefox, Opera 8.0+, Safari
                xmlHttp=new XMLHttpRequest();
        }
        catch (e)
        {
                // Internet Explorer
                try
                {
                        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e)
                {
                        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
                }
        }
        return xmlHttp;

}

--
Arjen
http://www.arjenkarel.nl
On May 9, 9:56 am, Arjen <d@mail.me> wrote:

I can't see a problem. It works for Firefox. Perhaps it's an IE issue?
On May 9, 9:56 am, Arjen <d@mail.me> wrote:

Just a suggestion, but if you want to load both divs at the same time,
why not implement the server-side protocol to send the contents for
both divs in one request as a JSON object, then you can loads them
both at the same time. Why make two separate requests when you can do
it in one, which will probably be quicker?
Daz schreef:

> On May 9, 9:56 am, Arjen <d@mail.me> wrote:
>> 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('ajaxreques t.php?action=reloaddiv2','div2')">verwijderen</a>

>> While both seperate actions work they dont when I put them together.
>> Anyone know how to fix this ?

> I can't see a problem. It works for Firefox. Perhaps it's an IE issue?

That's strange cause both in firefox(linux and windows) and ie it
doesn'work here;

The first div is filled corrctly but the second isn't
Here is an example
http://www.arjenkarel.nl/archief/4_Multiple-ajax-calls.php

--
Arjen

Daz schreef:

> On May 9, 9:56 am, Arjen <d@mail.me> wrote:
> Just a suggestion, but if you want to load both divs at the same time,
> why not implement the server-side protocol to send the contents for
> both divs in one request as a JSON object, then you can loads them
> both at the same time. Why make two separate requests when you can do
> it in one, which will probably be quicker?

Cool ... I had never heard of anything like that. Ill gonna look into it
right away. Im still verry curious however why the original doesn't work
. If anyone can shed some light on thaty I would appreciate it verry much

for an example see
http://www.arjenkarel.nl/archief/4_Multiple-ajax-calls.php

Arjen

--
Arjen
http://www.hondenpage.com

On May 9, 9:18 am, Floortje <l@zingmaarmetmijmee.enel> wrote:

One thing I noticed is that the onclick of the "Fill my divs" is
"show('/ajax.php?id=117','a');('/ajax.php?id=117','b');"
I think you probably want "show('/ajax.php?id=117','a');show('/
ajax.php?id=117','b');"
You're missing the second function name.

-jason

Jason schreef:

> One thing I noticed is that the onclick of the "Fill my divs" is
> "show('/ajax.php?id=117','a');('/ajax.php?id=117','b');"
> I think you probably want "show('/ajax.php?id=117','a');show('/
> ajax.php?id=117','b');"
> You're missing the second function name.

Whoops ... sorry copied the original too hasty (it's on a local site).
But after fixing it still only one div gets filled (div b). Im quite
clueless as to why. Apache logs show 2 requests.

--
Arjen

On May 9, 10:06 am, Floortje <l@zingmaarmetmijmee.enel> wrote:

> Jason schreef:

> > One thing I noticed is that the onclick of the "Fill my divs" is
> > "show('/ajax.php?id=117','a');('/ajax.php?id=117','b');"
> > I think you probably want "show('/ajax.php?id=117','a');show('/
> > ajax.php?id=117','b');"
> > You're missing the second function name.

> Whoops ... sorry copied the original too hasty (it's on a local site).
> But after fixing it still only one div gets filled (div b). Im quite
> clueless as to why. Apache logs show 2 requests.

> --
> Arjen

Can you post a link so that I can take a look using firebug. I think
the problem is that you are trying to do two requests at the same time
w/ the same request object and the response from only one of the
requests (the one that is completed the fastest) is the only one that
is coming back. If that is the problems (and I strongly suspect that
it is) you should take a look at YUI's connection manager. Someone
correct me if I'm wrong but to make two simultaneous requests you need
two instances of whatever your chosen request object is.

Arjen wrote:
> I want to reload 2 divs at one click. Ive tried:
> <a href = "javascript:void(0);"

Never use javascript pseudo-protocol HREFs, their execution on IE
versions prior to 7 has undesirable consequences that make it impossible
to determine what may or may not, should or should not, work in the
browser. Instead have the onclick handler cancel the navigation, or use
a more semantically appropriate element as the trigger (<input
type="button">, for example).

> 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

> var xmlHttp

This variable s being used to refer to the XML HTTP request objects. It
appears to be a global variable so there is precisely one slot in which
to store a reference to a single XML HTTP request object.

> var mydiv
> function show(str,div)
<snip>
> xmlHttp=GetXmlHttpObject()

Here each call to your - show - function assigns a reference to an XML
HTTP request object to the global variable (or an uncaught exception is
thrown).

> if (xmlHttp==null)
> {
> alert ("Browser does not support HTTP Request")
> return
> }
> var url=""
> url=url+str
> url=url+"&rnd="+Math.random()

This is a bad strategy for avoiding client-side caching of XML HTTP
responses. Random numbers may repeat, and do so in a relatively short
period. A non-repeating sequential value would be better, for which the
millisecond date is often preferred. As it is you have programmed a
system that will exhibit very intermittent faulty behaviour. Difficult
to spot, recreate and so correct.

> xmlHttp.onreadystatechange=stateChanged()

The above is assigning the return value from a call to - stateChange -
to the - onreadystatechange - of the XML HTTP request object. Your -
stateChange  - has no return statement so its return value is the
default Undefined value.  Thus this code, as posted , will never 'work'.
Posting code that is not the same as the code you are asking the
question about is counterproductive and a waste of everyone's time.

However, without the trailing parenthesise (the empty arguments list
that represents a 'call operator' in javascript) a reference to the
single - stateChanged - function object would be assigned to the -
onreadystatechange  - handler of each XML HTTP request object created,
and the code would 'work' in the way you describe (that is, badly).

> xmlHttp.open("GET",url,true)
> xmlHttp.send(null)
> }

> function stateChanged()
> {
> if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")

<snip>

Here is your (main) problem. Your - stateChanged - function is referring
to an XML HTTP request object via a global variable. The value of that
one global variable is a reference to the last XML HTTP request object
assigned to it. That will have been the assignment in the second call
to - show -, and so only the response from that second XML HTTP request
object will be handled at all.

> document.getElementById(mydiv).innerHTML=xmlHttp.responseText

<snip>

And it gets worse as you are also using a global variable to pass the ID
if the DIV into which the result will be inserted, so only the value of
the second assignment will be available and so only the second DIV will
be altered.

There are people who would suggest changing the XML HTTP requests from
asynchronous requests to synchronous, so the first must finish before
the second call to - show - can start. These people are halfwits who are
hiding from the issues inherent in AJAX instead of addressing them.

The real solution is to learn javascript programming and browser
scripting before even contemplating messing with something as inherently
complex as AJAX (with its implied requirement to marshal, organise and
sequence contexts in the face of at least two asynchronous sources of
input (the user and HTTP responses)). Learning javascript means
(eventually) learning how to use closures to preserve separate contexts
over time, which is how you should start to address this issue.

<snip>

This is irrational. There is very chance that this final attempt to
create an XML HTTP request object will throw and exception (is the user
has ActiveX disable in their browser, for example) so there should be a
try catch block around this call as well, and the return value from the
function call should be tested to see whether it is null or not.

It is also widely considered bad programming practice to use try/catch
blocks as program flow control structures, as you have above.  You can
verify whether a browser environment provides a global -
XMLHttpRequest - constructor or an - ActiveXObject - and use the results
of those tests to determine which branches the code should follow (which
also allows the exception to be avoided in environments that provide
neither).

Richard.

Mister Joe wrote:

<snip>

> ... . I think the problem is that you are trying to do
> two requests at the same time

Which would not be a problem as the limit on the number of simultaneous
asynchronous XML HTTP request that could be made would be whichever is
the smaller of the limit on the number of simultaneous HTTP connections
allowed by either the UA or the server.

> w/ the same request object

No, each call to the - show - function calls the - GetXmlHttpObject -
function, which (if it works at all) will return a new and distinct
instance of an XML HTTP request object.

> and the response from only one of the requests (the one
> that is completed the fastest) is the only one that
> is coming back.

Both requests are being made and both responses received. Both are
triggering - onreadystaechange - events but the function handling those
events is only paying attention to the readyState property of the _last_
object created, and only processing its contents (regardless of which
returns first).

> If that is the problems (and I strongly suspect that
> it is) you should take a look at YUI's connection manager.

That would be a very bad plan as it just ducks the issue, and bloats the
code with unneeded baggage along the way. While almost any AJAX
'library' written by a half decent programmer will be able to handle
multiple simultaneous requests without problems, switching to using one
while not understanding why the issue appeared in the first place just
means re-encountering the same issue in different contexts. Learning how
to program javascript is the best foundation for writing good javascript
programs.

> Someone correct me if I'm wrong

Done.

> but to make two simultaneous requests you need
> two instances of whatever your chosen request object is.

Yes, but two instances were created and used.

Richard.

Richard Cornford schreef:

> Arjen wrote:
>> I want to reload 2 divs at one click. Ive tried:
>> <a href = "javascript:void(0);"

> Never use javascript pseudo-protocol HREFs, their execution on IE
> versions prior to 7 has undesirable consequences that make it impossible
> to determine what may or may not, should or should not, work in the
> browser. Instead have the onclick handler cancel the navigation, or use
> a more semantically appropriate element as the trigger (<input

Got it. Ive been trying other stuff here
(http://www.hondenpage.com/fokkers/index.php). Im gonna read more about
it soon.

>> 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

>> var xmlHttp

> This variable s being used to refer to the XML HTTP request objects. It
> appears to be a global variable so there is precisely one slot in which
> to store a reference to a single XML HTTP request object.

I got it from the w3c school ajax example .. they usually have ok stuff.
I guess not this time.

>> var mydiv
>> function show(str,div)
> <snip>
>> xmlHttp=GetXmlHttpObject()

> Here each call to your - show - function assigns a reference to an XML
> HTTP request object to the global variable (or an uncaught exception is
> thrown).

Yup. I thought since there were 2 different calls the would be no problems.

>> if (xmlHttp==null)
>> {
>> alert ("Browser does not support HTTP Request")
>> return
>> }
>> var url=""
>> url=url+str
>> url=url+"&rnd="+Math.random()

> This is a bad strategy for avoiding client-side caching of XML HTTP
> responses. Random numbers may repeat, and do so in a relatively short
> period. A non-repeating sequential value would be better, for which the
> millisecond date is often preferred. As it is you have programmed a
> system that will exhibit very intermittent faulty behaviour. Difficult
> to spot, recreate and so correct.

Ok thx .. ill fix that asap :-)

>> xmlHttp.onreadystatechange=stateChanged()

> The above is assigning the return value from a call to - stateChange -
> to the - onreadystatechange - of the XML HTTP request object. Your -
> stateChange  - has no return statement so its return value is the
> default Undefined value.  Thus this code, as posted , will never 'work'.
> Posting code that is not the same as the code you are asking the
> question about is counterproductive and a waste of everyone's time.

It was was the code I was using at the time. I had been trying to pass
the variables instead of using them globaly but till that point
unseccesfully so I restored it back to the original code. I guess forgot
   to tremove the (). Last time i checked however it was still working
(badly). Im sorry i cant link to the original example because it's not
publicly available.

> However, without the trailing parenthesise (the empty arguments list
> that represents a 'call operator' in javascript) a reference to the
> single - stateChanged - function object would be assigned to the -
> onreadystatechange  - handler of each XML HTTP request object created,
> and the code would 'work' in the way you describe (that is, badly).

Im beginning to see :-)

>> xmlHttp.open("GET",url,true)
>> xmlHttp.send(null)
>> }

>> function stateChanged()
>> {
>> if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete")
> <snip>

> Here is your (main) problem. Your - stateChanged - function is referring
> to an XML HTTP request object via a global variable. The value of that
> one global variable is a reference to the last XML HTTP request object
> assigned to it. That will have been the assignment in the second call to
> - show -, and so only the response from that second XML HTTP request
> object will be handled at all.

Hmmm ... when you piont it out it seems so easy. I did spend a few hours
trying to rewrite and redo the script (with limited knowledge, hence the
() mistake )

>> document.getElementById(mydiv).innerHTML=xmlHttp.responseText
> <snip>

> And it gets worse as you are also using a global variable to pass the ID
> if the DIV into which the result will be inserted, so only the value of
> the second assignment will be available and so only the second DIV will
> be altered.

Yup .. same mistake.

> There are people who would suggest changing the XML HTTP requests from
> asynchronous requests to synchronous, so the first must finish before
> the second call to - show - can start. These people are halfwits who are
> hiding from the issues inherent in AJAX instead of addressing them.

I dont know about the halfwit part but I agree with you. I'd rather
understand what Im doing wrong so I can avoid the same mistake twice !

> The real solution is to learn javascript programming and browser
> scripting before even contemplating messing with something as inherently
> complex as AJAX (with its implied requirement to marshal, organise and
> sequence contexts in the face of at least two asynchronous sources of
> input (the user and HTTP responses)). Learning javascript means
> (eventually) learning how to use closures to preserve separate contexts
> over time, which is how you should start to address this issue.

I disagree. Atleast my mind doesn't work like that. I need to play with
the matter and create a feel for the context before I can really
understand. Learning is not all a static process where you can just read
a book and know the matter. It is finding the problem, looking for
solutions, assess the solutions and reevaluate your problem and the
solution. Especially when the matter is verry complex it's important to
play around with it to get a feeling of the context of he problem.

You seem to know a great deal about javascript so you might disagree but
if you someday descide you want to know about something you know verry
little about you will probably find yourself doing just that.

Hehe well as you might have noticed Im just starting to learn a little
javascript. I wish I had the time to take a week and learn the basics
but I just learn as i go along and try not to mess things up too badly :-).

I really thank you for your constructuve critticism and Im gonna fix
them errors righ away !

--
Arjen

On May 9, 6:34 pm, Floortje <l@zingmaarmetmijmee.enel> wrote:

OK, the problem (in a nut shell) is that mydiv is global. You make the
first request, and set mydiv to 'a', then the second request sets it
to 'b', so when the data is returned, both go into 'b' (the first is
overwritten by the second), as the show() function is using the mydiv
global variable. You need to look into closures. :)
On May 9, 6:34 pm, Floortje <l@zingmaarmetmijmee.enel> wrote:

Here's your script using closures. Note that mydiv and XMLHttp are no
longer global variables, and the call to stateChanged() is enclosed in
a function.

stateChanged() accepts two parameters. The id of the div to fill, and
the ajax requester object itself. Both of these are captured in the
closure.

This should work for you. But it's still not perfect. Any further
modifications are up to you to provide.

function show(str,div) {
        if (str.length==0) {
                document.getElementById(mydiv).innerHTML=""
                return
        }
        var xmlHttp=GetXmlHttpObject()
        if (xmlHttp==null) {
                alert ("Browser does not support HTTP Request")
                return
        }
        var url=""
        url=url+str
        url=url+"&rnd="+Math.random()
        xmlHttp.onreadystatechange=function() { stateChanged(oDiv,
xmlHttp); }
        xmlHttp.open("GET",url,true)
        xmlHttp.send(null)

}

function stateChanged(div,xmlHttp) {
        if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete") {
                document.getElementById('loading').innerHTML="";
                //alert(xmlHttp.responseText);
                document.getElementById(div).innerHTML=xmlHttp.responseText
        }
        else {
                document.getElementById('loading').innerHTML="<h1>Loading ....</
h1><img src = '/fw/images/loading.gif'>";
        }
}

function GetXmlHttpObject()
{
        var xmlHttp=null;
        try {
                // Firefox, Opera 8.0+, Safari
                xmlHttp=new XMLHttpRequest();
        }
        catch (e) {
                // Internet Explorer
                try
                {
                        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
                }
                catch (e) {
                        xmlHttp=new
ActiveXObject("Microsoft.XMLHTTP");
                }
        }
        return xmlHttp;

If you ever plan on compressing your code, you will need to start
making a habit of appending a semi-colon to the end of each line of
code, Don't take this literally, some lines of code won't work with
this, for example, an "if" statement.

On large scripts, you can compress it a certain amount my hand.
Basically, you use alias's which are functions and variables.

For example.

You used: document,getElementById();

As you use document and ...

read more »

Floortje wrote:
> Richard Cornford schreef:
>> Arjen wrote:
<snip>
>>> var xmlHttp

>> This variable s being used to refer to the XML HTTP request
>> objects. It appears to be a global variable so there is
>> precisely one slot in which to store a reference to a single
>> XML HTTP request object.

> I got it from the w3c school ajax example .. they usually have
> ok stuff. I guess not this time.

The view you take of w3c school probably depends on where you observe it
from. I would regard "ok stuff" as criminal exaggeration of what they
present.

<snip>

>>> xmlHttp.onreadystatechange=stateChanged()

>> The above is assigning the return value from a call to -
>> stateChange - to the - onreadystatechange - of the XML HTTP
>> request object. Your -  stateChange  - has no return statement
>> so its return value is the default Undefined value.  Thus this
>> code, as posted , will never 'work'. Posting code that is not
>> the same as the code you are asking the question about is
>> counterproductive and a waste of everyone's time.

> It was was the code I was using at the time. I had been trying
> to pass the variables instead of using them globaly but till
> that point unseccesfully so I restored it back to the original
> code. I guess forgot to tremove the (). Last time i checked
> however it was still working (badly).

Your 'checking' is then ineffective.

> Im sorry i cant link to the original example because it's not publicly
> available.

It would do you no good if you did as I read Usenet offline and would
never follow such a link.

<snip>

You mean you don't think it makes sense to try to learn the basics
before getting involved in the massively complex?

> I need to play with the matter and create a feel for the context
> before I can really understand.

And you will get a better feel for what you are doing by playing around
with simple scripts until you understand them before moving on to the
aspects of the subject that require complex and informed design
decisions to be made before even starting to write any code.

> Learning is not all a static process where you can just read a book
> and know the matter.

Did I say it was? And there are no books from which browser scripting
can be learnt.

> It is finding the problem, looking for solutions, assess the
> solutions and reevaluate your problem and the solution.

You are describing a process that results in people writing code that
consists of a loosely strung together aggregation of half-ass hacks.

There is a point where the problem takes the form of precise
specification (or can be expressed as one) and the solution is the
designing and then creating of systems and code that reliably satisfy
that specification.

> Especially when the matter is verry complex it's important to play
> around with it to get a feeling of the context of he problem.

> You seem to know a great deal about javascript so you might
> disagree but if you someday descide you want to know about
> something you know verry little about you will probably find
> yourself doing just that.

In the event that I wanted to learn, say, open-hart surgery, I would
probably start off with some basic biology qualification. Opening people
up and 'playing around' would be best left until a great deal else had
been learnt first.

<snip>

> Hehe well as you might have noticed Im just starting to learn a
> little javascript.

I have noticed that you are stumbling into an area where some of the
worst design and implementations mistakes are made (including by
significant and commercial public web sites like Google) without any
conception of one of the fundamental characteristics of the langue you
are trying to program with.

> I wish I had the time to take a week and learn the basics but I just
> learn as i go along and try not to mess things
> up too badly :-).

<snip>

So long as you never even suggest that anyone use anything you write in
any public context you cannot mess anything up too badly. Otherwise you
risk cutting someone's through and never realising you have done it.

Richard.

On May 9, 12:04 pm, "Richard Cornford" <Rich@litotes.demon.co.uk>
wrote:

Sorry Richard I mispoke I meant trying to do two request
simultaneously w/ the same request object.

>No, each call to the - show - function calls the - GetXmlHttpObject -

function, which (if it works at all) will return a new and distinct
instance of an XML HTTP request object.

Although the function returns a new request object each time it is
called the same global variable is being used to hold the reference to
the new request object.

>That would be a very bad plan as it just ducks the issue, and bloats the

code with unneeded baggage along the way. While almost any AJAX
'library' written by a half decent programmer will be able to handle
multiple simultaneous requests without problems, switching to using
one
while not understanding why the issue appeared in the first place just
means re-encountering the same issue in different contexts. Learning
how
to program javascript is the best foundation for writing good
javascript
programs.

Moreso than ducking the issue it allows him to see a working
implementation. Although the value of using preexisting libraries is
questionable (I personally try to stay away from them as much as
possible) depending on what you are trying to accomplish I do not
think you can argue against using a well documented library like YUI
as a learning tool and reference. After all the implementations that
he will find there has been proven to work across browsers and
platforms.

> In the event that I wanted to learn, say, open-hart surgery, I would
> probably start off with some basic biology qualification. Opening people
> up and 'playing around' would be best left until a great deal else had
> been learnt first.

And that is exactly how open heart surgery is not learned. They actually
open up (allready dead people) quite early on. Knowledge is a good thing
but even more important is context and experiences you have that enable
you to store and make sense of the knowledge.

Too bad this goes way beyond the scope of this group :-)

Anyway .. thx for the advice. Ill take it to heart and clean up my code !

--
Arjen
http://www.hondenpage.com

> function show(str,div) {
>    if (str.length==0) {
>            document.getElementById(mydiv).innerHTML=""
>            return
>    }
<<>>>
>         return xmlHttp;

Cool ! That did the trick ! Now om gonna get some sleep and in the
morning ill clean up the rest of the code !

It does help me ! Thx!
--
Arjen
http://www.hondenpage.com
Floortje said the following on 5/9/2007 1:34 PM:

The W3C has no "school site" from which to get an "ajax example". The
w3schools site has one though. It is of the same quality as all the rest
of the "school material" on the site, it is usually wrong and worth even
less than the ink it takes to view it on a monitor.

--
Randy
Chance Favors The Prepared Mind
comp.lang.javascript FAQ - http://jibbering.com/faq/index.html
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/

Add to del.icio.us | Digg this | Stumble it | Powered by Megasolutions Inc