Reputation: 5591
So, I have the following js function:
var name_list = names; //mike,steve,sean,roger
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: ({ action: 'some_function', name_list:name_list}),
success: function(data){
alert('success')
});
Here there is variable that hold an array of values ("mike,steve,sean,roger" separately by a comma).
Now, I want to use the first value to call an ajax (name_list = mike), and once it is done, I want to repeat the same ajax call with the second value (name_list = steve).
Here is my question.
How do I use individual value in the variable and only use the subsequent value when the function (ajax call) is successful?
Thanks!
Upvotes: 3
Views: 80
Reputation: 43910
I added a button to demonstrate that it works, use the console to observe.
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>SerialArrayFeed</title>
</head>
<body>
<button id="btn">Feed</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
jQuery.ajax({
type: "GET",
url: "_custom.ajax.url",
dataType: "html",
data: ({
action: serialArrayFeed,
names: arr
}),
success: function(data) {
if (data != undefined) {
alert('success');
}
}
});
var arr = ['mike', 'steve', 'sean', 'roger'];
var qty = arr.length;
function serialArrayFeed(arr) {
for (var i = 0; i < qty; i++) {
var next = arr.pop(i);
break;
return next;
}
console.log('arr: ' + arr + ' next: ' + next);
}
var btn = document.getElementById('btn');
btn.addEventListener('click', function(event) {
serialArrayFeed(arr);
}, false);
</script>
</body>
</html>
Upvotes: 1
Reputation: 144689
This is one way of doing it:
var name_list = ['mike','steve','sean','roger'];
function recursive(list, done) {
list = list.slice();
(function next() {
var name = list.shift();
jQuery.ajax({
type: "GET",
url: 'url',
dataType: 'html',
data: ({ action: 'some_function', name : name }),
success: function(data) {
console.log('success', name);
}
}).then(list.length ? next : done);
}());
}
recursive(name_list, function() {
console.log('all done');
});
Upvotes: 1
Reputation: 24001
simply try to make a function with ajax you want and pass values and on success run the ajax again till it reached to the last length of your array
var name_list = names.split(','); //mike,steve,sean,roger
var repeat_Ajax = function(i){
jQuery.ajax({
type: "GET",
url: custom.ajax_url,
dataType: 'html',
data: { action: 'some_function', name_list:name_list[i]}, // no need for `( )` here
success: function(data){
if(i !== name_list.length){
repeat_Ajax(i+1);
alert('success');
}
});
}
repeat_Ajax(0);
Untested code but I hope it work with you
Upvotes: 1