1

I have multiple fields in a form with same name, and I pass these values into ajax as;

$('#mybutton').click(function(){

  var flag = 0;

  $('input[name="myfield"]').each(function(){
    var current = $(this);
    var item = $.trim(current.val());
    if(item != ""){

      $.ajax({
        type: 'POST',
        url: 'ajaxhandler.php',
        data: 'myitem='+item,
        cache: false,
        success: function(result) {
          if(result == "true"){
            flag++;
          }
          alert("stage1 = "+flag);//returns flag (1,2,3 etc)
        }
      });

    }
  });

  alert("stage2 = "+flag);//returns 0. But I need same value as on the flag above
});

The flag is set to count the number of valid items, and is collected for further use. But outside ajax block, its not available. How can I solve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Alfred
  • 21,058
  • 61
  • 167
  • 249

2 Answers2

2

Your flag variable is local variable which declared inside of click event handler. And it will not be visible to outside of event handler. So you should simply declare it outside of event handler. If you want to use it inside of click event itself you can make your ajax query async:false or create function and call it after ajax call done.

Khamidulla
  • 2,927
  • 6
  • 35
  • 59
1

EDIT:

As the Ajax request is asynchronous then the alert("stage2 = "+flag); Is called right after your ajax call without waiting for the response. That is why flag=0

Merlin
  • 4,907
  • 2
  • 33
  • 51
  • Your are right, I've update my answer wich is not really a solution but might help to understand Ajax Call.. – Merlin Dec 27 '13 at 09:34