Ajax call in loop: Ajax requests getting cancelled except last - javascript

I have one ajax call in a loop as shown below.
reloadSetupAndRecurringAvailable = function( objDiscountRow ) {
var intProductId = objDiscountRow.find('.product-id').val();
var strUrl = '/?module=contract_setup_products-new&action=get_setup_and_recurring_available';
$.ajax( {
url: strUrl,
data: { 'product_id': intProductId },
success: function( response ) {
fltSetupAvailable = parseFloat( response.data.fltSetupAvailable );
fltRecurringAvailable = parseFloat( response.data.fltRecurringAvailable );
objDiscountRow.find('.setup-available').text( fltSetupAvailable + '%' );
objDiscountRow.find('.recurring-available').text( fltRecurringAvailable + '%' );
}
} );
reloadDiscountProducts = function() {
$('.discount-row').each( function() {
reloadSetupAndRecurringAvailable( $(this) );
} );
}
reloadDiscountProducts();
When the code executes, in the network tab the last ajax call shows successful and all the previous calls show in canceled status.
As per my findings it is due to asynchronization. The ajax request can take any time. How can I fix the code so that all the requests will be in completed status?

Related

Why does this jQuery AJAX loop fail with a 400 error after hundreds of successful loops?

I've written the code below which uses a $csv_rows array from PHP as data to be imported, each row is AJAXed and saved to the database. We've noticed it will 400 error at around 500+ rows (sometimes 1000+).
I've checked the network tab in Chrome debugger while the import is happening and there is no issue with the data being passed at the time of the error (the data shown is in the same format as previous rows which were successful).
jQuery( document ).ready( function( $ ) {
try {
var csvRows = $.parseJSON( '<?php echo json_encode( $csv_rows ); ?>' );
} catch( error ) {
alert(error);
}
var totalRows = csvRows.length - 1;
var rowsRemaining = csvRows.length - 1;
var rowsDone = 0;
function doAjax( $row ) {
// AJAX
var data = {
'action': 'import',
'row': csvRows[row],
};
// Do the ajax
$.ajax({
url: ajaxurl,
type: 'POST',
data: data,
success: function( response ) {
console.log( reseponse );
}
}).done( function() {
row = row + 1;
if ( row <= totalRows ) {
doAjax( row );
} else {
alert('Import complete');
}
rowsRemaining = rowsRemaining - 1;
rowsDone = rowsDone + 1;
}).fail( function( xhr, error, status ) {
alert( status );
});
}
row = 0;
doAjax( row );
});
This error occurs on the server side, so you will need to debug the server.
Since you mention PHP code, I assume it is served through a server like apache or nginx : check in the access log of this server if you see requests to your route which are answered with a 400 response code.
if you see them : you can debug the apache/nginx configuration and your PHP code
if you don't : the error happens between your own server and the browser, check other elements : are any proxies involved ? does your hoster have another service in front of your apache/nginx ? ...

My $(document).ajaxComplete() doesn't work

I'm messing with jQuery an AJAX for few days and I've come to a dead end. I'm trying to load some content with AJAX -this part works just fine - and after that I want to execute other script. However, my content loaded with first script doesn't show up till the second script is finished. Code looks like this:
$.ajax({
url : folder,
success: function (data) {
$(data).find("a").attr("href", function (i, val) {
if( val.match(/\.(jpe?g|png|gif)$/) ) {
var $codeText = "<li class='ui-state-default'><a href='#' data-featherlight='" + folder + val + "'><img src='" + thumbFolder + val + "' data-src='"+ thumbFolder + val + "'/></a></li>";
$("ul[id=sortable]").append($codeText);
$("li").featherlight(folder + val);
};
});
}
})
$(window).ajaxComplete(function(){
console.log("Haba");
var x = 0;
while( x < 50000 )
{
console.log("Haba nr "+x);
x++;
}
The whole code is triggered, but images are showing up on website after all the console messages. Does anyone have any suggestion what to do to show up pictures first? I've also tried with done(). and ajaxStop(), still no effect.
you have to use the .done() function of ajax to get the asynchrone result :
var jqxhr = $.ajax( "example.php" )
.done(function(data) {
alert( "success : " + data );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
Why not just move the code you want to run after the pictures are loaded into the success function of the ajax call and do that after the code to load pictures?
$.ajax({
url : folder,
success: function (data) {
//Code to load pictures
console.log("Haba");
var x = 0;
while( x < 50000 ) {
console.log("Haba nr "+x);
x++;
}
});
I think the reason it's not behaving the way you want it to is because the ajax call is complete after it gets a response back. That response triggers the ajax complete function that runs before your logic in the success function of the ajax call. Also, the way you have it written, the ajax complete logic will fire even if your ajax call fails. Which I don't think you want.
try to use setTimeout()
function ajaxDone(){
console.log("Haba");
var x = 0;
while( x < 50000 )
{
console.log("Haba nr "+x);
x++;
}
}
$(window).ajaxComplete(function(){
window.setTimeout(ajaxDone,1);
});

Jquery ajax call not firing

i'm making an app to track different craft beers i've tasted. part of that is making an AJAX call to set a cookie in the uder's browser -- i'm json_encoding the list.beerList array and trying to store it in a cookie. for some reason, the cookie is getting set, but Firebug isn't registering an AJAX call being made. and even when i send something back, the success condition of the jquery AJAX function isn't firing. code below:
angular.module( 'beerList', [] ).controller( 'beerListController', function($scope) {
var list = this;
list.beerList = [];
angular.element(document).ready( function() {
list.getCookie();
})
list.addBeer = function() {
var beerEntered = $( '#beer' ).val();
var breweryEntered = $( '#brewery' ).val();
var abvEntered = $( '#abv' ).val();
var notesEntered = $( '#notes' ).val();
list.beerList.push( { beer: beerEntered, brewery: breweryEntered, abv: abvEntered, notes: notesEntered } );
list.setCookie();
}
list.setCookie = function() {
var string = JSON.stringify(list.beerList);
$.ajax({
url: 'ABSOLUTE/PATH/TO/setCookie.php',
dataType: 'jsonp',
data: {
string: string
},
success: function(data) {
alert('success!');
}
})
}
list.getCookie = function() {}
})
thanks so much for your help!

Jquery when ; value not set

I need to repalce the href of a 'title' class elements in the page on the basis of the 0 or x value returned from http://kasaragodyellowpages.com/pagedata.php?id=x. this url is set to 1 for testing. work currectly to ajax requests.
problem is late response and failure in when
<script type="text/javascript">
$(document).ready(function(){
$('.title').each(function() {
var url = null;
var l = this.href;
id_str= (l.replace('http://www.kasaragodyellowpages.com/index.php?page=item&id=',''));
var loadUrl = "pagedata.php";
$.get(
loadUrl,
{id: id_str},
function(responseText){
if (responseText!=0) {
url='http://www.kasaragodyellowpages.com/index.php?page=page&id='+responseText;
console.log('data value for '+url);
}
}
);
if(url){
console.log('set data for '+url);
$(this).attr( 'href', url );
}else
{
console.log('NOT set data for '+url);
}
});
});
</script>
As in the image the ajax result is set after the setting the value from loop with out waiting for ajax success
After this i replaced with when
<script type="text/javascript">
$(document).ready(function(){
$('.title').each(function() {
var url = null;
var l = this.href;
id_str= (l.replace('http://www.kasaragodyellowpages.com/index.php?page=item&id=',''));
var loadUrl = "pagedata.php";
$.when($.get(
loadUrl,
{id: id_str},
function(responseText){
if (responseText!=0) {
url='http://www.kasaragodyellowpages.com/index.php?page=page&id='+responseText;
console.log('data value for '+url);
}
}
))
.then(if(url){
console.log('set data for '+url);
$(this).attr( 'href', url );
}else
{
console.log('NOT set data for '+url);
});
});
});
</script>
But this didn't work
in your first code, replace your call to $.get with
$('.title').each(function() {
var url = null;
var self = this;
.
.
.
.
$.get(
loadUrl,
{id: id_str},
function(responseText){
if (responseText!=0) {
url='http://www.kasaragodyellowpages.com/index.php?page=page&id='+responseText;
console.log('data value for '+url);
if(url){
console.log('set data for '+url);
$(self).attr( 'href', url );
}else
{
console.log('NOT set data for '+url);
}
}
}
);
The reason is $.get is an asynchronous call. Meaning, all code after $.get will be executed even if the response from $.get has not been received yet.

Javascript Returns Incorrect Value

I have a function which returns data from an AJAX call to determine if a user has any credits remaining and then displays the data accordingly. The strange thing is that the function does not return the expected result. Here is the code:
function setupBuildInputs() {
noCreditsError = '<div class="alert alert-danger">You have no build credits remaining, please contact a representative to purchase more.</div>';
if ( $('#newWebsiteBuildForm #user_id').length ) {
$('#newWebsiteBuildForm #user_id').change(function () {
userID = $(this).val();
jQuery.get(SITE_URL + '/ajax.php?action=getBuildCreditsRemaining&id=' + userID, function(numOfCredits) {
if ( numOfCredits > 0 ) {
// Get latest website URL and show it on the page
$('#websiteURLHolder').html('Updating...');
jQuery.get(SITE_URL + '/ajax.php?action=getNextWebsiteUsername&id=' + userID, function(data) {
$('#websiteURLHolder').html(data + '.checkoutyournewsite.com');
});
} else {
$('#quickBuildTagsHolder').html( noCreditsError );
}
});
});
}
$('#newWebsiteBuildForm #template').change(function () {
// Show the build form items
numOfRemainingCredits = checkBuildCredits( $('#newWebsiteBuildForm #user_id').val() );
alert(numOfRemainingCredits);
if ( numOfRemainingCredits > 0 ) {
$('#quickBuildTagsHolder').html('Updating...');
jQuery.get(SITE_URL + '/ajax.php?action=returnQuickBuildTags&template=' + $(this).val(), function(data) {
$('#quickBuildTagsHolder').html(data);
});
} else {
$('#quickBuildTagsHolder').html( noCreditsError );
}
});
}
function checkBuildCredits( userID ) {
buildCredits = 0;
jQuery.get(SITE_URL + '/ajax.php?action=getBuildCreditsRemaining&id=' + userID, function(data) {
buildCredits = data;
});
return buildCredits;
}
setupBuildInputs();
Using firebug I cans see that the call to ajax.php?action=getBuildCreditsRemaining pulls the correct id from the page and returns the correct value (9999). To debug further I added the alert on the second change event handler and the result is coming back as 0 instead of 9999.
Next I added 2 alerts to the even added an checkBuildCredits function. The first verified that the ajax call works and that data is set as 9999. The second strangely shows that buildCredits is still set to 0 right before the function returns.
In the setupBuildInputs function, the first change handler uses the same ajax call and it works fine, the second change handler which uses the functions of course fails since it doesn't get 9999 and instead sees 0.
Any ideas what is happening here?
replace checkBuildCredits with this
function checkBuildCredits( userID, successFn ) {
jQuery.get(SITE_URL + '/ajax.php?action=getBuildCreditsRemaining&id=' + userID, function(data) {
successFn(data);
});
}
Then when you call checkBuildCredits, do it like this
checkBuildCredits( $('#newWebsiteBuildForm #user_id').val(), function(numOfRemainingCredits )
{
if ( numOfRemainingCredits > 0 ) {
$('#quickBuildTagsHolder').html('Updating...');
jQuery.get(SITE_URL + '/ajax.php?action=returnQuickBuildTags&template=' + $(this).val(), function(data) {
$('#quickBuildTagsHolder').html(data);
});
} else {
$('#quickBuildTagsHolder').html( noCreditsError );
}
});
As the others have explained it, jquery.get is Asynchronous. And based on your design, you are treating jquery.get as a Synchronous call.
jquery.get is defaultly Asynchronous. so before your fetch the data,the function return the 0 value in your function checkBuildCredits
Instead of $.get() try using the following:
$.ajax({
url: SITE_URL + '/ajax.php?action=getBuildCreditsRemaining&id=' + userID,
success: function(data) {
buildCredits = data;
},
asynch: false
});
This will wait for the ajax call to complete before continuing script execution.

Categories

Resources