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?
 
     
     
    