Looping through functions with ajax calls - javascript

I'm currently looping through a number of functions that validate particular input values. One in particular requires an ajax call to validate an address. I saw that users here on SO suggested using callbacks to return the value.
The only problem is, by the time it does retrieve the value, the function had already fired within the loop and returned an undefined value. I've been searching around and wasn't sure what the best solution would be. Do I somehow delay the loop? Do I have my function setup right in the first place? Need some serious help.
var validations = [validateUsername, validatePassword, validateAddress];
function submitForm() {
var inputs = validations.map(function(validation) {
return validation();
});
return inputs.every(function(input) {
return input === true;
}); // [true, true, undefined]
}
function validateAddress() {
function addressIsValid(callback) {
$.ajax({
type: 'POST',
url: '/address/validate',
data: $form.serialize(),
dataType: 'json',
success: function(response) {
return callback(response.Data === 200);
}
});
}
function callback(response) {
return response;
}
return addressIsValid(callback);
}

You should use Promises.
First, you should make your asynchronous functions return a Promise:
function validateAddress() {
return new Promise((resolve, reject)=> {
$.ajax({
type: 'POST',
url: '/address/validate',
data: $form.serialize(),
dataType: 'json',
success: response=> {
response.Data === 200 ? resolve() : reject();
}
});
});
}
Then rewrite your submitForm function like this:
function submitForm() {
var promises = validations.map(validation=> validation());
return Promise.all(promises)
}
Then you can use submitForm like this:
submitForm()
.then(()=> {
// form is valid
}, ()=> {
// form is invalid
})

Related

How can I serve a "resolve" in my recursive AJAX calls so that I can use 'done'?

I am doing a few recurring AJAX calls where I pass an array from the front-end to the back-end and whenever it comes back to the front-end, the array gets smaller (by 1) and ultimately it'll be empty, therefore my recursive calls will stop.
Here's my calls:
function download_required_files(demo_data) {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
return false;
}
if(data.can_continue !== 'yes') {
return false;
}
if(data.remaining_steps && data.remaining_steps.length) {
demo_data.steps_to_take = data.remaining_steps;
download_required_files(demo_data);
}
$('.demo-loader-content').fadeOut();
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
Assuming I have 2 steps to download files for, this download_required_files will run twice, then it'll be done, but if I do:
var download_process = download_required_files(demo_data) //Runs 2 times
download_process.done(function() { //Do stuff here once that function ran 2 times });
It gives me the: Cannot read property 'done' of undefined error and for good reason. That download_process is not a promise object for it to have that property, it's just...empty.
Where should I intervene in my download_required_files so that it signals to outside code that "Hey, in a promise environment, I'm done!"?
Although the result of the call to $.ajax is a jqXHR object, which is promise-like, for what you describe I think I'd go with your own native Promise (or Deferred if you prefer) to represent the overall recursive process:
function download_required_files(demo_data) {
return new Promise(function(resolve, reject) {
function worker() {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
// *** All done
$('.demo-loader-content').fadeOut();
resolve();
} else if(data.can_continue !== 'yes') {
// *** All done; but is this an error condition? If so
// use `reject` instead of `resolve` below.
$('.demo-loader-content').fadeOut();
resolve();
} else {
demo_data.steps_to_take = data.remaining_steps;
worker(); // This is the internal recursive call
}
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
worker();
});
}
Or using Deferred instead:
function download_required_files(demo_data) {
var d = $.Deferred();
function worker() {
var ajaxsecurity = setup_page_params.ajax_nonce;
jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: ajaxsecurity,
content_install_request_data: JSON.stringify(demo_data),
},
success: function (response) {
console.log(response);
var data = response.data || false;
/**
* If no steps are left, meaning that all required files have been downloaded, proceed with the whole install process.
*/
if(!data.remaining_steps || !data.remaining_steps.length) {
// *** All done
$('.demo-loader-content').fadeOut();
d.resolve();
} else if(data.can_continue !== 'yes') {
// *** All done; but is this an error condition? If so
// use `d.reject` instead of `d.resolve` below.
$('.demo-loader-content').fadeOut();
d.resolve();
} else {
demo_data.steps_to_take = data.remaining_steps;
worker(); // This is the internal recursive call
}
},
error: function (response) {
$('.demo-loader-content').fadeOut();
}
});
}
worker();
return d.promise();
}
This would be my approach, separating the individual AJAX requests from the looping over the content, and that also from the DOM updates:
function download_one_file(demo_data) {
return jQuery.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: {
action: 'download_import_files_request',
security: setup_page_params.ajax_nonce,
content_install_request_data: JSON.stringify(demo_data),
}
});
}
function download_loop(demo_data) {
return download_one_file(demo_data).then(function(data) {
if (!data) {
return Promise.reject();
} else if (data.remaining_steps && data.remaining_steps.length) {
demo_data.steps_to_take = data.remaining_steps;
return download_loop(demo_data);
} else {
return Promise.resolve();
}
});
}
function download_required_files(demo_data) {
return download_loop(demo_data).finally(function() {
$('.demo-loader-content').fadeOut();
});
}

JQuery AJAX - Filter before .done()

My application has a lot of AJAX calls, each of them return a JSON response. Instead of validating the data in each of the the .done() calls, I'm trying compact the code.
What we have so far
$.ajax({
url: 'test',
type: 'GET',
data: {
_token: token
},
dataFilter: function(jsonResponse) {
return isValidJson(jsonResponse);
}
}).done(function(jsonResponse) {
// do things
});
isValidJson(jsonResponse) {
try {
var parsedJson = $.parseJSON(jsonResponse);
if (parsedJson.error == 1) {
notificationController.handleNotification(parsedJson.message, 'error');
return false;
}
} catch (err) {
notificationController.handleNotification('A server-side error occured. Try refreshing if the problem persists.', 'error');
return false;
}
return jsonResponse; // Have to return the original data not true
}
The expected behavior is that if dataFilter returns false, it will trigger .fail(), if it returns true then it will continue to .done(). Instead, it just continues to .done() with the result of isValidJson().
Is there also a way to make .fail() do something standard like send a notification to the user without having to put it under every AJAX call?
Easiest way is to create a shorthand for $.ajax, by extending it.
Extending the AJAX call
jQuery.extend({
myAjax: function(params){
// Here we can modify the parameters and override them e.g. making 'error:' do something different
// If we want to add a default 'error:' callback
params.error = function() {
console.log('its failed');
};
// or you can specify data parse here
if (params.success && typeof params.success == 'function') {
var successCallback = params.success;
var ourCallback = function(responseJson) {
if (isValidJson(responseJson)) { // Validate the data
console.log('The json is valid');
successCallback(responseJson); // Continue to function
} else {
console.log('The json is not valid');
}
}
params.success = ourCallback;
}
return $.ajax(params);
}
});
Now everytime you want to make an AJAX call in your application, you DO NOT use $.ajax({}). Instead, you use $.myAjax({});
Example
$.myAjax({
url: 'domain.com',
type: 'GET',
success: function(data) {
// Do what you'd do normally, the data here is definitely JSON.
},
error: function(data) {}
});
And this special function will handle all errors same way, no need to write those validators every time.
Try to do it like this (Not tested):
var jxhr = $.ajax({
url: 'test',
type: 'GET',
data: {
_token: token
},
dataFilter: function(jsonResponse) {
if (!isValidJson(jsonResponse)) {
jxhr.abort();
}
return jsonResponse;
}
}).done(function(jsonResponse) {
// do things
});
By using this strategy - you are violating "separation of concern" strategy.
Ajax should resolve or reject according to its action. Not according if response is JSON or not.
A possible solution : ( sure there are also another solutions)
function GetSanitized(d) {
return d.then(function(a) {
if (a.indexOf('{') > -1) //check if json ( just for example)
return $.Deferred().resolve(JSON.parse(a)); //return object
else
return $.Deferred().reject(a); //reject
},
function() {
return $.Deferred().reject("ajax error"); //ajax failed
}
);
}
var ajax = $.Deferred();
GetSanitized(ajax) .then(function (a){alert(" Json p's value is "+a["p"]);},function (a){alert("Error"+a);});
ajax.resolve("{\"p\":2}"); //simulate ajax ok , valid json
//ajax.resolve("\"p\":2}"); //simulate ajax ok , invalid json
//ajax.reject("\"p\":2}"); //simulate ajax bad , valid json
http://jsbin.com/vozoqonuda/2/edit

Jquery When and Deferred object, broken function flow

I am using $.when and .done to make sure that the close window happens after the data is saved. But, this doesn't seem to work as expected.
The workflow is that, user clicks on a button "Save and Close", which should save the data first, trigger print and close the window. But the save data and close window happens at the same time which makes the print fail.
I have read about when..then and deferred object. Tried to implement it here the following code, sometimes it work but most of the time it would break.
$("#btnSaveAndClose").click(function (event) {
$.when(zSaveSomeData()).done(function (value) {
zCloseMyWindow();
});
});
function zSaveSomeData() {
return zSaveMasterData(masterdata, function () {
return zSaveDetailData();
});
};
function zSaveMasterData(masterdata, fnAfterSave) {
return $.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/masterdata/',
data: JSON.stringify(masterdata),
success: function (data) {
fnAfterSave();
}
});
};
function zSaveDetailData() {
var selectedDataGroups;
// some logic here
zSaveDetails(selectedDataGroups);
};
function zSaveDetails(selectedDataGroups) {
var deferred = $.Deferred();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/detaildata/',
data: JSON.stringify(selectedDataGroups),
success: function (data) {
var printableGroupIDs = [];
$.each(data, function () {
if (this.IsPrintable)
printableGroupIDs.push(this.ID);
});
if (printableGroupIDs.length > 0) {
zPrintGroups(printableGroupIDs);
}
deferred.resolve('done');
}
});
zAuditSave();
return deferred.promise();
};
function zPrintGroups(newGroupIDs) {
// calls external program to print groups
};
function zCloseWindow() {
window.close();
};
function zAuditSave() {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/audit'
success: function (data) {
}
});
};
Only thing is that the save calls other methods inside to same master and details data. There are couple of ajax calls too. An unusual thing is that after the data is saved, there is a call to VB code that actually triggers a Print. I am so confused on why would close window fire before the other methods are executed. Any help would be appreciated.
For me the code is overly divided into functions, with some doing little more than fronting for others.
I would prefer to see the click handler as a comprehensive master routine which sequences three promise-returning functions zSaveMasterData(), zSaveDetails() and zAuditSave(), then closes the window. Thus, some of the current functions will be subsumed by the click handler.
$("#btnSaveAndClose").click(function(event) {
zSaveMasterData(masterdata).then(function() {
var selectedDataGroups;
/* some logic here */
var detailsSaved = zSaveDetails(selectedDataGroups).then(function(data) {
var printableGroupIDs = $.map(data, function (obj) {
return obj.IsPrintable ? obj.ID : null;
});
if (printableGroupIDs.length > 0) {
// calls external program to print groups
}
});
// Here, it is assumed that zSaveDetails() and zAuditSave() can be performed in parallel.
// If the calls need to be sequential, then the code will be slightly different.
return $.when(detailsSaved, zAuditSave());
}).then(function() {
window.close();
});
});
function zSaveMasterData(masterdata) {
return $.ajax({
type: 'POST',
url: '/api/masterdata/',
contentType: 'application/json',
data: JSON.stringify(masterdata),
});
};
function zSaveDetails(selectedDataGroups) {
return $.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/detaildata/',
data: JSON.stringify(selectedDataGroups)
});
};
function zAuditSave() {
return $.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/audit'
});
};
Note the returns in the three functions with ajax calls. These returns are vital to the sequencing process.
A potentially bigger issue, not addressed in the question (nor in this answer) is how to recover from errors. Presumably, the database will be inconsistent if the sequence of saves was to fail part way through. It may well be better to ditch this client-side sequencing approach in favour of a server-side transaction that the client sees as a single operation.
The problem here is your code doesn't depend on when fnAfterSave() has completed.
Short answer: don't mix success methods, callbacks, and promises - use one pattern and stick to it - and the easiest pattern to use is promises.
$("#btnSaveAndClose").click(function (event) {
zSaveSomeData().then(function() { zCloseMyWindow(); });
});
function zSaveSomeData() {
return zSaveMasterData(masterdata).then(function(data) { zSaveDetailData() });
};
function zSaveMasterData(masterdata) {
return $.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/masterdata/',
data: JSON.stringify(masterdata)
});
//remove success callback here as it breaks the chaining
};
It seems like your problem is that you are doing asynchronous things inside an ajax success callback. The promise returned by $.ajax still resolves immediately after the response is received - and executes your done callback before the asynchronous zSaveDetailData() has finished.
So, to chain asynchronous actions, always use then. Use it even for synchronous actions, it makes the sequence clear.
Don't use success callbacks when you're working with promises. You also don't need deferreds. You might want to have a look at these generic rules as well, especially that you never must forget to return promises from async functions that you want to await.
$("#btnSaveAndClose").click(function (event) {
zSaveSomeData().then(zCloseMyWindow);
});
function zSaveSomeData() {
return zSaveMasterData(masterdata).then(zSaveDetailData);
}
function zSaveMasterData(masterdata) {
return $.ajax({
type: 'POST',
contentType: 'application/json',
url: '/api/masterdata/',
data: JSON.stringify(masterdata),
});
}
function zSaveDetailData() {
var selectedDataGroups;
// some logic here
return zSaveDetails(selectedDataGroups);
// ^^^^^^
}
function zSaveOrderGroups(selectedDataGroups) {
return $.ajax({
// ^^^^^^
type: 'POST',
contentType: 'application/json',
url: '/api/detaildata/',
data: JSON.stringify(selectedDataGroups)
}).then(function(data) {
// ^^^^^^^^^^^^^^^^^^^^^^
var printableGroupIDs = [];
$.each(data, function () {
if (this.IsPrintable)
printableGroupIDs.push(this.ID);
});
if (printableGroupIDs.length > 0) {
return zPrintGroups(printableGroupIDs);
// ^^^^^^
}
}).then(zAuditSave);
// ^^^^^^^^^^^^^^^^^
}
function zPrintGroups(newGroupIDs) {
// calls external program to print groups
}
function zCloseWindow() {
window.close();
}
function zAuditSave() {
return $.ajax({
// ^^^^^^
type: 'POST',
contentType: 'application/json',
url: '/api/audit'
});
}

returned array is undefined, not async

For some reason my function is returning undefined while seemingly working in itself.
function getDomains() {
$.ajax({
url: '/rewrites/cgi-bin/ajax.pl?action=listdomains',
dataType:'json',
async: false,
success: function( data ) {
if (data.error) {
alert(data.error);
}
else {
alert(data.domains);
return(data.domains);
}
}
});
}
alert(getDomains());
My first alert shows a populated list but the second is undefined. Does this make any sense?
You're in a function for the success call. That's why you're not getting a result from your getDomains function. Assign it to a variable and return the variable after the ajax call.
function getDomains() {
var results;
$.ajax({
url: '/rewrites/cgi-bin/ajax.pl?action=listdomains',
dataType:'json',
async: false,
success: function( data ) {
if (data.error) {
alert(data.error);
}
else {
alert(data.domains);
results = data.domains;
}
}
});
return results;
}
alert(getDomains());
Why don't you just do this, assuming you need your return for a function called whateverFunc():
function getDomains() {
$.ajax({
url: '/rewrites/cgi-bin/ajax.pl?action=listdomains',
dataType:'json',
async: false,
success: function( data ) {
if (data.error) {
alert(data.error);
}
else {
whateverFunc(data.domains);
}
}
});
}
function whateverFunc(domains){
alert(domains);
}
You can't return anything from success callback, it makes no sense.
I would like also to complain about the async:false here. Why do you need it absolutely?
You should let the call be async and manage the blocked state by yourself with some mutex or something around. In fact, you should trigger popup or whatever you need to do after you get the answer in the whateverFunc().
It's clean and you keep control on the blocking state.

use different parameter for a success callback

I'm working on someone else's code. I have this simple AJAX call in jQuery:
function getWSData (which, data, idVR)
{
if(which == 'verCandAll')
{
funcSuccess = verCandSuccess;
data = {'name' : 'val'};
}
else
{
funcSuccess = verElseSuccess;
data = {'name2' : 'val2'};
}
$.ajax({
type: 'POST',
url: wsURL,
data: data,
success: funcSuccess,
error:function ()
{
$("#msg").ajaxError(function()
{
popWaiting(false);
alert(verGenericCallError);
});
},
dataType: 'xml'
});
}
function verCandSuccess(xml){ ... }
function verElseSuccess(xml){ ... }
It's really simple. The only problem I have is the success callback. In case of verElseSuccess I would send a second parameter to that function, more precisely i would handle the idVR (an input parameter of getWSData). How can I accomplish this?
To achieve this, you can do:
...
if(which == 'verCandAll') {
...
}
else {
// create an anonymous function that calls verElseSuccess with a second argument
funcSuccess = function(xml) {
verElseSuccess(xml, idVR);
};
data = {'name2' : 'val2'};
}
...
Use Underscore.js partial function:
funcSuccess = _.partial(verElseSuccess, idVR);

Categories