tags:

views:

144

answers:

4

Hey all,

somehow still not able to do what I’m inted to do. It gives me the last value in loop on click not sure why. Here I want the value which is been clicked.

Here is my code:

$(document).ready(function() {
  var link = $('a[id]').size();
  //alert(link);
  var i=1;
  while (i<=link)
   {
 $('#payment_'+i).click(function(){
   //alert($("#pro_path_"+i).val());
  $.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){ 
   //alert(data);
   $("#container").html(data);    
  });
 });
 i++;
   }
});

Here the placement_1, placement_2 .... are the hrefs and the pro_path is the value I want to post, the value is defined in the hidden input type with id as pro_path_1, pro_path_2, etc. and here the hrefs varies for different users so in the code I have $('a[id]').size(). Somehow when execute and alert I get last value in the loop and I don’t want that, it should be that value which is clicked.

I think onready event it should have parsed the document and the values inside the loop I’m not sure where I went wrong. Please help me to get my intended result.

Thanks, all

A: 

You have to use a local copy of i:

$('#payment_'+i).click(function(){
    var i = i;  // copies global i to local i
    $.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_"+i).val()}, function(data){ 
        $("#container").html(data);
    });
});

Otherwise the callback function will use the global i.

Gumbo
+1  A: 

I would suggest using the startsWith attribute filter and getting rid of the while loop:

$(document).ready(function() {
    $('a[id^=payment_]').each(function() {

        //extract the number from the current id
        var num = $(this).attr('id').split('_')[1];

        $(this).click(function(){    
            $.post("<?php echo $base; ?>form/setpropath/", {pro_path: $("#pro_path_" + num).val()},function(data){ 
                $("#container").html(data);    
            });
        });
    });
});
karim79
hey thanks for the solun it worked like a charm i did not had to a single change in the code ...
mainu raj kehte hai
A: 

Here is a note on multiple/concurrent Asynchronous Requests:

Since you are sending multiple requests via AJAX you should keep in mind that only 2 concurrent requests are supported by browsers.

So it is only natural that you get only the response from the last request.

andreas
He's not sending simultaneous requests, but rather he's binding multiple click handlers each with different $.post parameters.
karim79
A: 

What if you added a class to each of the links and do something like this

$(function() {
 $('.paymentbutton').click(function(e) {
  $.post("<?php echo $base; ?>form/setpropath/",
   {pro_path: $(this).val()},
   function(data) {
    $("#container").html(data);
   });
  });
 });
});

Note the use of $(this) to get the link that was clicked.

Samuel