1

I m using jQuery-step library with a form combining the formvalidation.js . i want to delay below method response until ajax complete.

i want to send return true/false when ajax complete.

onStepChanging: function (e, currentIndex, newIndex) {

    var fv = $stepForm.data('formValidation'), // FormValidation instance
        // The current step container
        $container = $stepForm.find('section[data-step="' + currentIndex + '"]');

    // Validate the container
    fv.validateContainer($container);
    var isValidStep = fv.isValidContainer($container);
    if (isValidStep === false || isValidStep === null) {
        // Do not jump to the next step
        return false;
    }
    if (isValidStep === true) {
        //call ajax here
        //wait for ajax to complete then move to next or keep 
    }
    return true; //-> i want to delay this 

},
Noman
  • 4,088
  • 1
  • 21
  • 36

2 Answers2

0

I have done by setting property in javascript window then wrap the return in setTimeout function

Step 1:

$(document).ready(function(){ window.flag = ''; });

Step 2

function submitForm($stepForm) { 
    $.ajax({
        type: 'POST',
        url: 'http://' + location.host + "/ajax",
        dataType: 'JSON',
        data: {'method': 'submitApplication', 'formdata': $stepForm.serialize()},
        success: function (data) {
          window.flag = true;
        }
}

Step 3:

onStepChanging: function (e, currentIndex, newIndex) {
  if (isValidStep === true) {
                submitForm($stepForm);
  }
 .... code
  setTimeout(function () {
     return window.flag;
  }, 2000);
}
Noman
  • 4,088
  • 1
  • 21
  • 36
  • Why you need the setTimeout ? Just make the submitForm function a promise an do something on the callback function! – funcoding Mar 30 '17 at 11:48
  • @Noman , Ajax are async calls, u can never tell if your ajax call will always complete in 2 seconds delay that you have set. Also as per your code you dont deed that 2 second of time out....just set if (isValidStep === true) { return submitForm($stepForm); and return true/false in "submitForm" function. } – JoshulSharma Mar 30 '17 at 13:00
0

In your case:

function submitForm($stepForm) {
    return new Promise((resolve, reject) =>{
      $.ajax({
        type: 'POST',
        url: 'http://' + location.host + "/ajax",
        dataType: 'JSON',
        data: {'method': 'submitApplication', 'formdata': $stepForm.serialize()},
        /* Resolving true on success, you could also return a json object if you need the response */ 
        success: () => { resolve(true); },
        /* Rejecting the promise in case of an error */
        error: () => { reject(false) } 
     })
  })
}

Then:

onStepChanging: function (e, currentIndex, newIndex) {
  if (isValidStep === true) {
       submitForm($stepForm)
       .then( /*...Do whatever you want ..*/)
       .catch( console.log );
  }
funcoding
  • 741
  • 6
  • 11