JQuery. Ajax request for each row in table
ajax, jquery
Solution
The issue is that AJAX requests are asynchronous so if you do all of them within .each() there will be no pause.
What you need is to first take each of the `el` elements and place them in an array. Then create a global variable that will be your counter to know how many requests have been sent.
You send your first request, and then send the second in the success function of the first, and so on.
You need to rewrite essentially, so that requests are sent as previous is finished.
Example:
function test()
{
var arr = new Array();
var counter = 0;
$('.data').each(function(i, el) {
arr.push(el);
});
doRequest(counter);
function doRequest(counter)
{
var query = $(arr[counter]).children('.editable').children('.query').text();
var page = $(arr[counter]).children('.editable').children('.page').text();
$.ajax({
url: 'http://www.google.com?'+query+'&page='+page,
success: function(data){
alert("made request with query="+ query);
counter++;
if(counter<arr.length)
doRequest(counter);
}
});
}
}
Edit:
As I saw from the other answers you can just include `async: false,` which makes the requests asynchronous.
An approach similar to this is only useful for situations where `async:false` is not supported, or not preferable due to blocking the browser...
Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active.
From: http://api.jquery.com/jQuery.ajax/#jQuery-ajax-settings
Problem
I tried do Ajax request for each row in table, but i can't achieve the desired result Table: ``` <table> <tr class="data"> <td class="editable"> <a class="refresh btn btn-large" class="page"> Col one </a> </td> <td class="editable"> <a href="#" data-pk="10" id="query" class="query"> Col two </a> </td> </tr> <tr class="data"> <td class="editable"> <a class="refresh btn btn-large" class="page"> Col one 1 </a> </td> <td class="editable"> <a href="#" data-pk="10" id="query" class="query"> Col two 1 </a> </td> </tr> </table> ``` Ajax Request ``` $("#detect_rel").click(function(){ $('.data').each(function(i, el) { var query = $(el).children('.editable').children('.query').text(); var page = $(el).children('.editable').children('.page').text(); $.ajax({ url: 'wordstat/ajax?query='+query+'&page='+page, success: function(data){ $(el).children('.editable').children('.relevantnost').html(data) } }); }); }); ``` My problem: All ajax requests are sent at the one time, but i need do pause between requests. P.s. About attribute "id" in tags: i should use it cuz of "Bootstrap X Editor"