I need to use jQuery each function but also need it to work from the first element to the last. Currently it seems to just be choosing random elements that match the criteria.
Here’s what I have:
$(".ago-time").each(function(index) {
var old_ts = $(this).data("ts2");
$.get("phpscripts/get_new_time.php", {
old_ts: old_ts,
index: index
}, function(result) {});
alert(result);
});
The index and old_ts are sent off to a php file where the output will be something like 0: 1 minute ago.
What I am getting in the alert is not in order (from 0 to highest). It will be something like this;
First alert:9: 10 mins ago
Second alert: 2: 4 mins ago
Third alert 5: 8 mins ago
As you can see the alerts are not in order of index so the each function must be selecting the ago-time‘s randomly.
eachdoes iterates sequentially over the matched elements over a jQuery object but the misunderstanding here is another.$.getis a shorthand$.ajaxfunction, that’s an asynchronous HTTP request. The callback function, in this case:is called asynchronously as you get the responses from the server.
But, for what it seems, in your case this is irrelevant and a misunderstanding from you while trying to debug the server responses.
For instance, in your code you can simply set the responses as you receive them from the server to their respective DOM elements.