Repeating a function using an array of values

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') }); 

There is a variable that stores an array of values ​​("mike, steve, sean, roger" separately by a comma).

Now I want to use the first value to call ajax (name_list = mike), and as soon as this is done, I want to repeat the same ajax call with the second value (name_list = steve).

Here is my question.

How to use an individual value in a variable and use only the subsequent value when the function (ajax call) is successful?

Thanks!

+3
source share
3 answers

This is one way to do this:

 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'); }); 
+1
source

try to make the function with ajax that you want and pass the values ​​and if ajax starts successfully again until it reaches the last length 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); 

Unconfirmed code, but I hope it works with you.

+1
source

I added a button to demonstrate that it works, and use the console for monitoring.

 <!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> 
+1
source

Source: https://habr.com/ru/post/1238457/


All Articles