Tuesday 29 March 2016

javascript - Pause the function execution flow till ajax request completes



I seem to be running into the typical "Asynchronous Problem", with the solution eluding me.



I have a bootstrap form wizard which is just an improvised tabs/slideshow kinda thingy. All my "Steps" are forms each inside respective tabs/slides.



It has a set of next/previous buttons to navigate around the slides.

And It provides a function callback on before moving to next slide.
Inside which(callback) I am "client-side validating" the form in current slide and if its validated then I am submitting the form using ajax. And once I get the response from server, I am deciding whether to return true (proceed to next slide) or return false (stop the navigation to next slide).



I have looked into ..




  • Using callbacks but then it wont stop the plugin from proceeding to next slide, which btw is a hard coded success message, so while we are waiting for the ajax response the wizard has already moved to the next slide.

  • Using async:false but this hangs the browser like crazy(by design), till the request is completed, so sans the hanging this is exactly what I want.




My code is as below.



JS.



  jQuery('#progressWizard').bootstrapWizard({
'nextSelector': '.next',
'previousSelector': '.previous',
onNext: function (tab, navigation, index) {
if (index == 1) { // Here I am deciding which code to execute based on the current slide/tab (index)
if (jQuery("#paymentstep1").data('bValidator').validate()) {

var data = new FormData(jQuery('#paymentstep1')[0]);
jQuery("#cgloader").fadeIn();
var success = false;
jQuery.ajax({
type: "post",
async: false,
contentType: false,
processData: false,
url: "xyz.php",
dataType: "json",

data: data,
success: function (r) {

return r;
}
});
}....

Answer



The docs for onNext say:





Fired when next button is clicked (return false to disable
moving to the next step)




So simply return false from your handler. In the AJAX success callback, call next to advance to the next slide.



var requestCompleted = false;
jQuery('#progressWizard').bootstrapWizard({

'nextSelector': '.next',
'previousSelector': '.previous',
onNext: function (tab, navigation, index) {
if (index == 1) { // Here I am deciding which code to execute based on the current slide/tab (index)
if (jQuery("#paymentstep1").data('bValidator').validate()) {
if(!requestCompleted) {
var data = new FormData(jQuery('#paymentstep1')[0]);
jQuery("#cgloader").fadeIn();
var success = false;
jQuery.ajax({

type: "post",
url: "xyz.php",
data: data,
// ...
success: function (r) {
requestCompleted = true;
jQuery('#progressWizard').bootstrapWizard('next');
return r;
}
});

return false;
}
}
}
});

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...