bart2puck bart2puck - 1 month ago 12
jQuery Question

ajax calls iterating through javascript array

I am trying iterate through a series of inputs from a form. foreach input i want to fire an ajax call that will only fire after previous call was completed.
I read a Stack answer here.

$(function(){

var data = [];

$('input[type=text]').each(function(e,i){
var val = $(this).val();
data.push(val);
});

current = 0;
function do_ajax() {
if (current < data.length) {
$.ajax({
type:"POST",
data:"id="+data[current].value,
url:"tester.php",
success:function(result){
$('#div').append(result);
current++;
do_ajax();
}
});
};
}
do_ajax();
});


HTML

<input type='text' id='users[][name]' value='Bob'>
<input type='text' id='users[][name]' value='Frank'>
<input type='text' id='users[][name]' value='Tom'>
<input type='text' id='users[][name]' value='Joe'>
<input type='text' id='users[][name]' value='Bill'>
<input type='text' id='users[][name]' value='Gary'>

<div id='done'></div>
<div id='div'>DIV</div>


tester.php for testing is simply:

echo $_POST['id'];


i cant get anything returned from tester.php except:

undefined


what do i need to put for id in the data section of ajax call?

I have tried:

data[current].value;

data[current].val;

data[current].val();

Answer

There's no value property, change this:

data:"id="+data[current].value

to this:

data:"id="+data[current]

and also use complete instead of success callback because complete executes after success and error callback

Comments