Callback function after jQuery ajax call - javascript

I have a function which makes a jQuery ajax call to a REST endpoint. This function will be run 5-6 times with different endpoints to collect data to validate against. During this time I would like to display a spinner on the browser screen to indicate to the end user that the program is processing. I'd like to then hide the spinner once complete. I'm struggling to figure out how to get this to work. My thought would be a simple callback function. I've tried putting the callback function in the click method and the css method as well as directly in the ajax call (validateAcctStr) and none of these seem to work. I feel like there is something simple I am missing?
$(document).ready(function(){
$("#submit").click(function(disableSpinner){
$("#json-overlay").css("display", "block");
validateAcctStr("ValidationAccount", "#accountTxt", "#acctValid");
validateAcctStr("ValidationBusiness", "#businessTxt", "#busValid");
});
function disableSpinner(){
$("#json-overlay").css("display", "none");
alert("test");
}
});
This is what I have so far for my ajax call (it pulls data from a SharePoint list):
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){
$.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"});
}
});
}
});
}

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.

Related

Show waiting dialog on synchronous ajax

I want to show a waiting dialog while a synchronous ajax is made.
I using a Smart Wizard, to change between step one to step to i have to validate some data to do that i have to make 3 ajax call one after the other and while this is done i want to show a waiting dialog. This is what I'm doing.
if (indexes.fromStep==1) {
res=false;
var validatorResult = validator.checkAll($("#install_modbus_form"))
if (validatorResult) {
$("#modal_loader").modal()
$.ajax({
type: "post",
url: url1,
async: false,
dataType: "json",
data:{
data
},
success: function(response)
{
if (response.success)
{
$.ajax({
type: "post",
url: url2,
async: false,
dataType: "json",
data:{
data
},
success: function(response)
{
if (response.success)
{
$.ajax({
type: "post",
url: url3,
async: false,
dataType: "json",
data:{
data
},
success: function(response)
{
if (response.success)
{
//make magic here
res=true;
}
},
failure:function()
{
waitingDialog.hide()
res=false
},
error:function(a,b,c) {
waitingDialog.hide()
res=false
}
)
}
},
failure:function()
{
waitingDialog.hide()
res=false
},
error:function(a,b,c) {
waitingDialog.hide()
res=false
}
)
}
},
failure:function()
{
waitingDialog.hide()
res=false
},
error:function(a,b,c) {
waitingDialog.hide()
res=false
}
)
$("#modal_loader").modal('hide')
return res;//if true change step
}
}
I have trie use beforeSend to show the waiting dialog, also i have trie to use setTimeout but the waiting dialog is not show and the smart wizard dont go forward
Hope you can help, Im new in jquery.
Sorry for the bad english
On the assumption that you are using jQuery-Smart-Wizard, the solution lies in :
the construction of your onLeaveStep event handler, and (or including)
a modified version of the validation code shown in the question.
Fortunately, even though the plugin does not natively support asynchronism, it is fairly simple to make it do so. Essentially, what you need to do is :
to return false from the onLeaveStep callback,
to establish a promise which fulfills on successful validation, or rejects on failure,
to call .smartWizard('goForward') from the promise's success handler,
to call .smartWizard('showError') from the promise's error handler.
Based on smartWizard's ReadMe.md, here's a framework for performing synchronous and asynchronous validations :
$(document).ready(function() {
var waitingDialog = $('#whatever'); // ???
// Smart Wizard
$('#wizard').smartWizard({
onLeaveStep: leaveAStepCallback,
onFinish: onFinishCallback
});
function leaveAStepCallback(obj, context) {
alert("Leaving step " + context.fromStep + " to go to step " + context.toStep);
var returnValue;
switch(context.fromStep) {
case 1: // asynchronous
if (validator.checkAll($("#install_modbus_form"))) {
$("#modal_loader").modal();
waitingDialog.show();
validateStep1() // validateStep1() returns a promise
.then(function() {
// You will arrive here only if all three ajax calls were successful and all three responded with a truthy `response.success`.
$('#wizard').smartWizard('goForward'); // advance to next step
}, function(e) {
// You will arrive here on validation failure
$('#wizard').smartWizard('showError', e.message); // something went wrong
}).always(function() {
// You will arrive here on validation success or failure
waitingDialog.hide(); // the waiting is over
$("#modal_loader").modal('hide'); // ???
});
} else {
$('#wizard').smartWizard('showError', 'validator.checkAll() failed');
}
returnValue = false; // *must* return false to remain at step 1. If validation is successful, `.smartWizard('goForward')` will be executed later (see above).
break;
case 2: // synchronous
returnValue = validateStep2(); // validateStep2() returns true of false
break;
case 3:
...
break;
}
return returnValue; // true or false
}
// And here's the all-important `validateStep1()` :
function validateStep1() {
var sequence = [
{ url: 'url/1', data: {...} },
{ url: 'url/2', data: {...} },
{ url: 'url/3', data: {...} }
];
return sequence.reduce(function(promise, item, i) {
return promise.then(function() {
return $.ajax({
'type': 'post',
'url': item.url,
'dataType': 'json',
'data': item.data
}).then(function(response, textStatus, jqXHR) {
return response.success ? response : $.Deferred().reject(jqXHR, 'response.success not truthy at validation stage ' + i); // note: need to mimic jQuery.ajax's error signature.
});
});
}, $.when()) // starter promise for the reduction
.then(null, function(jqXHR, textStatus, errorThrown) {
return $.Deferred().reject(new Error(textStatus || errorThrown));
});
}
function validateStep2() {
// if validation here is synchronous, then return true of false
if(....) {
return true;
} else {
return false;
}
}
function validateStep3() {
...
}
// etc.
function onFinishCallback(objs, context) {
if(validateAllSteps()) {
$('form').submit();
}
}
function validateAllSteps() {
var isStepValid = true;
// all step validation logic
return isStepValid;
}
});
Notes :
the branching logic is in the onLeaveStep callback.
validateStep1() uses a chained promise pattern to sequence the three ajax calls.
if validateAllSteps() needs to repeat the step1 validation, then you will need call validateStep1().then(...) again, or chain from a previously cached promise.
As you can see, some aspects above are incomplete so there's still some work to do.

.focusout() fires twice on second event jQuery

When I am using the .focusout() function in jQuery it seems to fire twice when I trigger the event for the second time, here is an example of my code:
$(document).ready(function() {
var baseUrl = "http://annuityadvicecentre.dev/";
if($('html').hasClass('ver--prize-soft')) {
$('#home_telephone').focusout(function () {
var softResponse = {};
var inputVal = $(this).val();
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "mobile",
},
error: function() {
console.log('POST Error: Mobile');
},
}).done(function(data) {
// you may safely use results here
softResponse.isMobile = data;
});
$.ajax({
type: 'POST',
url: baseUrl + "lookup",
data: {
number: inputVal,
phone_type: "landline",
},
error: function() {
console.log('POST Error: Landline');
},
}).done(function(data) {
// you may safely use results here
softResponse.isLandline = data;
});
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
});
}
});
Sorry for the messy example as I have just been bootstrapping this up however you can see I am wrapping this focusout function:
$('#home_telephone').focusout(function () {...
Around my AJAX calls, now for some reason when I test this out on the page and un-focus on the #home_telephone element the .ajaxStop() function only runs once which is the functionality I want however if I then click on the element and un-focus again the .ajaxStop() function runs twice. Any idea why this might be happening? Thanks
Try to add e.stoppropogation() within function like:
$('#home_telephone').focusout(function (e) {
e.stopPropagation()();
//your code
});
You're adding a new ajaxStop listener every time the element is unfocused. Just move the:
$(document).ajaxStop(function () {
console.log('All AJAX Requests Have Stopped');
});
call outside of the focusout callback function.

jquery date picker is not work when i put datepicker on ready after ajax call

I want to know that my jquery-ui datepicker is not working in document.ready after an ajax function call. when I put on ajax complete its work successfully please help what should I do. what's the reason for not working
$("#ScheduledArrivalDate").datepicker({
beforeShow: function () {
setTimeout(function () {
$('.ui-datepicker').css('z-index', 2000);
}, 0);
}
});
function getPage(page) {
$.ajax({
type: "POST",
url: page,
data: $("#frm").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
$('#List').empty();
$('#List').append($.parseHTML(html));
},
error: function () {
alert("error");
},
complete: function () {
alert("complete");
}
});
}
$.document.ready() only initiates after a page is loaded without ajax. When you replace/append html in an ajax call and you have a datefield in the new inserted html, you need to initialise it again (at least for the new inserted html block).
You could do this by calling $.datepicker in your success or complete function, like you already did, or by adding $.document.ajaxEnd() to your javascript file, what is initialized after every end of an ajax event (also on error).
Be aware not do double initiate the datepicker, especially when using ajaxEnd. This could lead to unexpected behaviour.
the code inside $(document).ready() will run only after page loads. While you are dynamically adding datepicker if I am not wrong. So do one thig. Take options in a variable like below:
var options = {
beforeShow: function () {
setTimeout(function () {
$('.ui-datepicker').css('z-index', 2000);
}, 0);
}
}
then:
$(document).ready(function(){
$("#ScheduledArrivalDate").datepicker(options);
});
and in ajax call:
function getPage(page) {
$.ajax({
type: "POST",
url: page,
data: $("#frm").serialize(),
xhrFields: {
withCredentials: true
},
success: function (html) {
$('#List').empty();
$('#List').append($.parseHTML(html));
$('#IdOfnewlyAddedDatePicker').datepicker(options);
},
error: function () {
alert("error");
},
complete: function () {
alert("complete");
}
});
}
Let me know if this not work or you are injecting html other than this.

Extending jQuery ajax success globally

I'm trying to create a global handler that gets called before the ajax success callback. I do a lot of ajax calls with my app, and if it is an error I return a specific structure, so I need to something to run before success runs to check the response data to see if it contains an error code bit like 1/0
Sample response
{"code": "0", "message": "your code is broken"}
or
{"code": "1", "data": "return some data"}
I can't find a way to do this in jQuery out of the box, looked at prefilters, ajaxSetup and other available methods, but they don't quite pull it off, the bets I could come up with is hacking the ajax method itself a little bit:
var oFn = $.ajax;
$.ajax = function(options, a, b, c)
{
if(options.success)
{
var oFn2 = options.success;
options.success = function(response)
{
//check the response code and do some processing
ajaxPostProcess(response);
//if no error run the success function otherwise don't bother
if(response.code > 0) oFn2(response);
}
}
oFn(options, a, b, c);
};
I've been using this for a while and it works fine, but was wondering if there is a better way to do it, or something I missed in the jQuery docs.
You can build your own AJAX handler instead of using the default ajax:
var ns = {};
ns.ajax = function(options,callback){
var defaults = { //set the defaults
success: function(data){ //hijack the success handler
if(check(data)){ //checks
callback(data); //if pass, call the callback
}
}
};
$.extend(options,defaults); //merge passed options to defaults
return $.ajax(options); //send request
}
so your call, instead of $.ajax, you now use;
ns.ajax({options},function(data){
//do whatever you want with the success data
});
This solution transparently adds a custom success handler to every $.ajax() call using the duck punching technique
(function() {
var _oldAjax = $.ajax;
$.ajax = function(options) {
$.extend(options, {
success: function() {
// do your stuff
}
});
return _oldAjax(options);
};
})();
Here's a couple suggestions:
var MADE_UP_JSON_RESPONSE = {
code: 1,
message: 'my company still uses IE6'
};
function ajaxHandler(resp) {
if (resp.code == 0) ajaxSuccess(resp);
if (resp.code == 1) ajaxFail(resp);
}
function ajaxSuccess(data) {
console.log(data);
}
function ajaxFail(data) {
alert('fml...' + data.message);
}
$(function() {
//
// setup with ajaxSuccess() and call ajax as usual
//
$(document).ajaxSuccess(function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
$.post('/echo/json/');
// ----------------------------------------------------
// or
// ----------------------------------------------------
//
// declare the handler right in your ajax call
//
$.post('/echo/json/', function() {
ajaxHandler(MADE_UP_JSON_RESPONSE);
});
});​
Working: http://jsfiddle.net/pF5cb/3/
Here is the most basic example:
$.ajaxSetup({
success: function(data){
//default code here
}
});
Feel free to look up the documentation on $.ajaxSetup()
this is your call to ajax method
function getData(newUrl, newData, callBack) {
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
url: newUrl,
data: newData,
dataType: "json",
ajaxSuccess: function () { alert('ajaxSuccess'); },
success: function (response) {
callBack(true, response);
if (callBack == null || callBack == undefined) {
callBack(false, null);
}
},
error: function () {
callBack(false, null);
}
});
}
and after that callback success or method success
$(document).ajaxStart(function () {
alert('ajax ajaxStart called');
});
$(document).ajaxSuccess(function () {
alert('ajax gvPerson ajaxSuccess called');
});

How to return a value inside AJAX function to parent in javascript?

I'm trying to return true or false to a function depending on the response of an AJAX function inside of it but I'm not sure how should I do it.
(function($) {
$('#example').ajaxForm({
beforeSubmit : function(arr, $form, options) {
var jsonStuff = JSON.stringify({ stuff: 'test' });
$.post('/echo/json/', { json: jsonStuff }, function(resp) {
if (resp.stuff !== $('#test').val()) {
// Cancel form submittion
alert('Need to type "test"');
return false; // This doesn't work
}
}, 'json');
},
success : function() {
alert('Form sent!');
}
});
})(jQuery);​
I made a fiddle to illustrate this better:
http://jsfiddle.net/vengiss/3W5qe/
I'm using jQuery and the Malsup's Ajax Form plugin but I believe this behavior is independent of the plugin, I just need to return false to the beforeSubmit function depending on the POST request so the form doesn't get submitted every time. Could anyone point me in the right direction?
Thanks in advance!
This is not possible to do when dealing with async functions. The function which calls post will return immediately while the ajax call back will return at some point in the future. It's not possible to return a future result from the present.
Instead what you need to do is pass a callback to the original function. This function will eventually be called with the result of the ajax call
var makePostCall = function(callback) {
$.post('/echo/json/', { json: jsonStuff }, function(resp) {
if (resp.stuff !== $('#test').val()) {
// Cancel form submittion
alert('Need to type "test"');
callback(false);
} else {
callback(true);
}}, 'json');
};
Then switch the code which expected a prompt response from makePostCall to using a callback instead.
// Synchronous version
if (makePostCall()) {
// True code
} else {
// false code
}
// Async version
makePostCall(function (result) {
if (result) {
// True code
} else {
// False code
}
});
you can put async:false parameter to ajax request then you can control future responce and send back the result to parent. see following main lines enclosed within ***
add: function (e, data) {
//before upload file check server has that file already uploaded
***var flag=false;***
$.ajax(
{
type: "POST",
dataType:'json',
url:"xyz.jsp",
***async:false,***
data:{
filename : upload_filename,
docname : upload_docname,
userid : upload_userid,
},
success:function(data)
{
***flag=true;***
},
error:function(request,errorType,errorMessage)
{
alert ('error - '+errorType+'with message - '+errorMessage);
}
});
***return flag;***
}

Categories

Resources