I am new to jquery deferred and I spent a while looking at similar questions on here but to no avail. I could use some help
I have a function that grabs the form input values and a function that saves those values. The form inputs values are not being grabbed fast enough before the save items function executes. I am trying to solve this by using jquery deferred but cannot get it to work. I also tried to use .when and .done. When I hard coded the parameters in my js file, Attempt 2 worked but not when I passed parameters on an onclick or in my console.
Any help would be appreciated!
Attempt 1:
function deferredTest1(w,x,y,z) {
var d1 = $.Deferred();
d1.done(function() {
SaveNewItem(x,y,z);
});
function getFormValues(w) {
$(w).each(function(i,obj) {
var input = $(this).val();
var inputID = $(this).attr('id');
str = str.concat(",'"+inputID+"':'"+input+"'");
});
}
d1.resolve();
}
Attempt 2:
function deferredTest2(w,x,y,z) {
var formvalues = getFormValues(w);
$.when(formvalues).done(SaveNewItem(x,y,z));
}
Your second try was closest. The
$.when
call takes a deferred, so we create one first, then use that in the$.when
call. It is resolved in thegetFormValues
method after the loop is completed. At this time thethen
callback is executed.There is no asynchronous action here though, so a deferred is not necessary. A deferred is used to manage various asynchronous requests and their callbacks if they depend on one another.