Repeating a function using array of values
Ad
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!
Ad
Answer
Ad
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');
});
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad