On Jun 10, 7:44 am, psc <petercar...@gmail.com> wrote:
> I am very new to javascript/jquery so bare with me. I am using this
> loop code below with a populated array called "listarray":
>
>         for(var i in listarray){

Don't use for..in to iterate over an Array, it can be problematic
unless you have complete control over the environment.  Use a normal
for, while or do loop.


>                 var currententry = listarray[i];
>                 var finalurl="phpscript.php?entry="+currententry;
>                 jQuery.ajax({
>                   url: finalurl,

Here, the value of finalurl has a closure to the "outer" finalurl...

>                   success: function(serverreply){
>                   alert(currententry);
>                 }
>                 });

Your AJAX request likely runs asynchronously, so the loop has finished
before the first request is sent.  At that point, finalurl has the
last value it was assigned for all the waiting xmlHTTPRequests.

You can either make the calls synchronous (probably a bad idea) or
break the closure.

>         }
>
> The alerts will always be the exact same: the last item in the array.
> So if there are 10 items in the array, it will alert the last one...
> 10 times. I'm trying to work with each entry, but I think my code
> might be mixed up.

Classic symptoms of an unexpected closure.

>
> The script is a very dumbed down version of what I'm working on, but
> it's where I'm having my problem. I need to be able to see the ajax
> reply, and depending upon what that reply is, do something with the
> current array entry. If I alert() the serverreply instead... that
> works fine and gives different responses each time... but when I alert
> () the "currententry" it's the last item in the array every time.

Likely the alert pauses the loop long enough for the request to be
sent with the current value of finalurl. Read about closures (the
following article is long and detailed, but stick with it as you'll
learn a lot about ECMAScript in the meantime):

<URL: http://www.jibbering.com/faq/faq_notes/closures.html >


--
Rob

Reply via email to