Ajax Request Callback Using Jquery

Javascript callback function in ajax request

Use then() for each instance. A return does nothing in success as it is not part of the promise chain

Basic example

function doAjax() {
// sample data that will be returned
var json = '{"foo":[1,2,3]}'

return $.ajax({...}).then(function(resp){
// return to next "then()" in promise chain
return resp.foo
})
}


doAjax().then(function(data){
console.log(data) // [1,2,3]
})

DEMO

Callback function after jQuery ajax call

You have almost all pieces in place, just have to put the thing in the proper order.

The issue is that you never call the disableSpinner function.

As you have several other small things, I'll show you changing your code.

So your $(document).ready() staff will became:

$(document).ready(function(){
$("#submit").click(function(ev){
activeSpinner();
validateAcctStr("ValidationAccount", "#accountTxt", "#acctValid");
validateAcctStr("ValidationBusiness", "#businessTxt", "#busValid");
});
});

When you have the other javascript code:

// You worked well wrapping the code to disable the spinner in a function
// let's do it for the activation too.
function activeSpinner() {
$("#json-overlay").css("display", "block");
}

function disableSpinner() {
$("#json-overlay").css("display", "none");
// this is just for test:
// alert("test");
}

And the ajax call:

function validateAcctStr(list, inputField, validationField) {
$.ajax({
url: "https://urlAddress/_api/web/lists/getbytitle('"+list+"')/items?$orderby=Title asc&$top=4999",
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
},
success: function(data){
disableSpinner(); // As the first task you have to disable the spinner.
$.each(data.d.results, function(index, item){
var arrayVar = $(inputField).val();
if(item.Title === arrayVar){
$(validationField).html("Valid").css({"background-color": "green", "color": "white", "text-align": "center"});
return false;
} else {
$(validationField).html("Invalid").css({"background-color": "red", "color": "white", "text-align": "center"});
}
});
},
error: function(err) {
disableSpinner(); // to avoid spinner active on an error
// do something with the error.
}
});
}

UPDATE

If you need to wait untill a list of callbacks are complete, than you should use a slighty complicated approach.

You could introduce promises, but you have to rewrite almost all your code.
in your case you should use callbacks:

function callbackCounter () {
var count = 0;
return {
set: function (n) {
count = n;
},
incr: function () {
cont++;
},
done: function() {
count--;
},
doneAll: function() {
count = 0;
},
isDone: function() {
return count === 0;
}
}
}

// ...
$("#submit").click(function(ev){
activeSpinner();
var countCallbacks = callbackCounter ();
countCallbacks.set(2);
validateAcctStr("ValidationAccount", "#accountTxt", "#acctValid", countCallbacks);
validateAcctStr("ValidationBusiness", "#businessTxt", "#busValid", countCallbacks);
});

function validateAcctStr(list, inputField, validationField, countCallbacks) {

// snipp...
success: function(data){
// here you decrement the callbacks:
countCallbacks.done();
if (countCallbacks.isDone()) disableSpinner(); // As the first task you have to disable the spinner.
},

The same code in the error handler.

AJAX request callback using jQuery

The elegant way would be to have a separate(!) PHP file that will only output the number times 2 part of your current PHP. Then you generate an AJAX request from your current PHP to the new separate PHP.

Callback when AJAX calls are done using jQuery when

Part of the issue is that your using ajax requests which could occur either before or after the code happens to handle those executions. Since they are async, its possible that they could fire/return before any other code runs on the page depending on how your browser's Javascript parser decides to execute the code. Rather than attempting to use Callbacks on asynchronous ajax requests, you can control the entire interaction by using a small 600 byte library called ajaxq.js

ajaxq.js essentially works just like jQuery's $.post() method, only you can also specify multiple queues by name to execute asyncronously, and attach a callback to them or whatever.

Here's a quick example of how you could setup your Ajax Cart Preview using this library.

/* queue up an AJAX request */
$.postq("set_data", "add_items.php", {"itemID": someItemID, "customerID": customerID },
function(result1) {


/* perform new request at the end of first request */

$.postq("get_data", "get_items.php", { "id": customerID },
function(result2) {

/* add in code to perform at the end of the second ajax POST request */

}); // end of request 2

}); // end of request 1

Here's your example using the ajaxq.js library:

function AddToCart(input) {
$.postq("add_item", "/cart/add/js", input, function(result) {
preview_items();
}, "json");

}

function preview_items() {
$.getJSON('/cart.js', function(data) {
$('.cart-item-count').text(data.item_count);
$('.cart-item-price').html(formatMoney(data.total_price));
ShowCart();
}


$(document).ready(function() {
$("#addToCart").on("click" function() {
$('#capsContainer input:checked').each(function(elem) {
var cartItem = {
id: $(this).val(),
quantity: 1
}

cart.push(cartItem);
});

var test1 = AddToCart(cart[0]);
var test2 = AddToCart(cart[1]);

});

jQuery AJAX post callback doesn't seems to work

If you use $.ajax instead of $.post ($.post is really an overwrite of $.ajax with fewer parameters), you can add a handler for error and see if it fires:

jQuery.ajax({
type: "POST",
async: true,
url: '/offers/1/voting',
data: { 'direction': 'up' },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});

pass data through a ajax request to a callback function

Wrap the call to the provided callback in an anonymous function. Try this:

function rquest(callback, passData){
$.ajax({
type: "POST",
url: someURL,
success: function(data) {
callback(data, passData)
}
});
};

function myCallback(data, passData) {
var responseData = data;
var SomeOtherData = passData
//do Something
};

rquest(myCallback, "Hello World");


Related Topics



Leave a reply



Submit