I have a button which when clicked opens a modal(dashboard_name) in which user enters some value. Based on the value after he clicks submit on that modal I call another function which opens another modal and user enters a different value there and finally when he clicks submit on this modal, I call an api to verify everything is correct.
Now, the problem is when I click on the first button to open the modal the execution doesn't wait for the function to get the data from the dashboard_name modal and then the graph_name modal. Instead it directly jumps to the api function call, which is right coz that's how jQuery works. But I wanted to know how to use deferred and promise to make this execution serial.
Function for the first button when clicked.
$('#add_to_dash').click(function(e){
dashboard_submit();
graph_submit();
});
this function gets the dashboard modal and tries to get the value.
function dashboard_submit(){
//do something
}
this function after success of the dashboard_submit function tries to get value for the graph modal
function graph_submit(){
//do something
}
and then on form submit i call this following func
<form name="form2" onsubmit="return isDashboardCorrect(dashboard_name);" method="post" action="{{ url_for('dashboards_new') }}">
the function
function isDashboardCorrect(dashboard_name) {
var flag=0;
$.ajax({
async: false,
type: 'GET',
url: 'xyz.com/dashboard/'+dashboard_name,
success: function(data) {
//alert(data);
//do something
});
}
I want all of this to be sequential which is not happening right now i.e. when i click on the first button it doesn`t wait for the functions to execute and directly the isdashboardcorrect() function gets called.
I want the order to be 1. button click 2. dashboard_submit() 3. graph_submit() 4. isdashboardcorrect() serially.
I tried something simpler like
$('#add_to_dash').click(function(e){
alert('addtodashstart');
dashboard_submit().done(function(){
alert('done');
});
alert('addtodashend');
});
function dashboard_submit()
{
alert('dashboardsubmot');
var dfd = new $.Deferred();
$("#d_name_modal_div").modal({backdrop: false}).modal("show");
$('#d_name_modal_submit').on('click', function(){
dashboard_name=$('#dashboard_name').val();
alert(dashboard_name);
if(dashboard_name==null || dashboard_name.trim()=='')
{
alert('Dashboard name is mandatory.');
return false;
}
else
{
dfd.resolve();
return dfd.promise();
}
});
}
When I click the button I call the dashboard_submit function. But here too it doesn`t wait for
`$('#d_name_modal_submit').on('click', function(){
this to execute in the above function and directly hits the api function. What Am i doing wrong?`
Example fiddle : http://jsfiddle.net/LKP66/18/