While looping a jquery ajax call
It doesn't work for a simple reason: the $.ajax
call is asynchronous.
Take this example:
$(function() { var t = 1; console.log("Hey, the ajax will start! t's value: " + t); $.ajax({ url: 'www.google.com.br', method: 'GET', success: function (data) { t++; console.log("We've received an answer! t's (incremented) value: " + t); }, error: function (xhr, status, error) { t++; console.log("We've received an error! t's (incremented) value: " + t); } }); console.log("Hey, the ajax just ended.... Not really. t's value: " + t);});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
While loop with jQuery async AJAX calls
Your best bet would be to restructure your code to use async ajax calls and launch the next call when the first one completes and so on. This will allow the page to redisplay between image fetches.
This will also give the browser a chance to breathe and take care of its other housekeeping and not think that maybe it's locked up or hung.
And, use async: 'false'
is a bad idea. I see no reason why properly structured code couldn't use asynchronous ajax calls here and not hang the browser while you're fetching this data.
You could do it with asynchronous ajax like this:
function getAllImages(position, maxImages) {
var imgCount = 0;
function getNextImage() {
$.ajax({
url: urlAJAX + 'scan=' + position,
method: 'GET',
async: true,
success: function(data) {
if (data.status == "success" && imgCount <= maxImages) {
++imgCount;
renderImageData(data);
getNextImage();
}
}
});
}
getNextImage();
}
// no while loop is needed
// just call getAllImages() and pass it the
// position and the maxImages you want to retrieve
getAllImages('front', 20);
Also, while this may look like recursion, it isn't really recursion because of the async nature of the ajax call. getNextImage()
has actually completed before the next one is called so it isn't technically recursion.
Ajax call inside a while loop
jQuery ajax (as most ajax implementations), which $.get()
is a shorthand for, is asynchronouos be default. The callback function is only executed once the request is complete. The while continues indefinitely since without yielding control out to the JS engine the callback doesn't get a chance to do it's work - even if the request(s) are done.
In order to continuously send requests, try like this:
function requestMore(i) {
$.get('/my/url/?get=' + i, function (data) {
if (data != '') {
sortArticles(data);
requestMore(i + 1);
}
});
}
(document).ready(function () {
requestMore(1);
});
Ajax Update within the While Loop - JQuery
Element with id
must be unique on the page. So, creating tens of <input type='text' id='mov' />
is not correct. You should use "dynamic" ids instead, for example:
echo "<input type='text' id='mov-" . $row['MOVIEID'] . "' name='movie' maxlength='8' pattern='[0-9]{8}' value='" . $row['MOVIEID'] . "'>";
echo "<button class='button_save' data-id='" . $row['MOVIEID'] . "'>Save</button>";
I suppose, your $row['MOVIEID']
stores unique values. And because of that, id='mov-" . $row['MOVIEID'] . "'
are strings like mov-2
, mov-3
, mov-10
etc.
Now in your js you can:
var val2 = $(this).attr("data-id"); // Get the ID of the button that was clicked on
var val1 = $('#mov-' + val2).val(); // value from `input` which is connected the clicked button
$.ajax({ // AJAX request
type: 'POST',
url: 'mov_update.php',
data: { text1: val1, text2: val2 },
success: function(response) {
// $('#result').html(response);
//$('#mov').val(val1); // updates input new value
// not sure what this is for, as field value is already `val1`
$('#mov-' + val2).val(val1);
}
});
JQuery ajax() inside for loop
$.ajax({
type: "POST",
url: "/New/GetOnState",
contentType: "application/json; charset=utf-8",
data: '{"country":"' + countryValue + '"}',
dataType: "html",
async:false,
success: function (result, status, xhr) {
// alert("success");
// alert(arrayID[index]);
ddlStateidElement = "ddlState_" + ido;
$('#' + ddlStateidElement).html(result);
//index = index + 1;
},
error: function (xhr, status, error) {
alert("Enter");
}
});
How can I loop over over multiple ajax requests, and then execute code after everything has been complete?
If you capture the Promise (technically a jQuery Deferred object, actually) generated by each AJAX request, and add them to an array, then you can call .when()
to execute some code once all of the Promises are resolved. Something like this (untested):
var myItems = myObj.items;
var promises = [];
$(myItems).each(function(index, item) {
var itemUrl = '/somestuff/' + item.url + '.js';
var p = $.getJSON(itemUrl);
p.then(function(itemData) {
item.data = itemData;
return itemData;
});
promises.push(p);
});
$.when.apply($, promises).then(function() { //render data to template...
This is probably preferable to chaining the done() callbacks, because it still allows the requests to execute in parallel, which is likely to be faster (although this is somewhat dependent on the server, but that's a separate issue).
jQuery ajax call in php while loop only returns first id
$('.price')
returns a collection and while there are some functions (like .css()
) that operate directly on them, .attr()
only operates on individual elements, so it's only returning the value of the first one:
console.log($('.price').length)console.log($('.price').attr('id'))
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><div class="price" id="id1" value="value1"></div><div class="price" id="id2" value="value2"></div>
Related Topics
Deselect All Options in Multiple Select With 1 Option
Usestate Hook Not Updating a Value
Sum Numbers in HTML Inputs, JavaScript
How to Pass Value to a Onclick Function in (Jade)Pug
React.Js - Input Losing Focus When Rerendering
Getting Typeerror: This.Props Is Undefined on Reactjs
Angular 2 Not Updating Until Any Object Is Clicked
How to Set Profile Image as First Letters of First and Last Name
How to Style Dynamically Created Elements With CSS
How to Convert a Htmlelement to a String
Multi Select Drop Down With Checkbox
Is It Okay to Call Onclick on an Anchor Tag in Reactjs
Does JavaScript Guarantee Object Property Order
Click on Element Containing Text in Puppeteer
Map, and Removing Commas from an Array in JavaScript