1

I'm using jQuery-steps in a legacy codebase.

The point is, I'm trying to make it dynamic and I'm stuck at asynchronistic nature of form validation.

This plugin creates a multi-step form, and you can click next to navigate to the next tab.

However, there is this onStepChanging: function (event, currentIndex, priorIndex) function that can be used to prevent navigation to the next tab, if form is invalid.

It works great for synchronous fields. That is, this code works great:

onStepChanging: function (event, currentIndex, newIndex) {
    if ($('#username').val() === '') {
        return false;
    }
    return true;
}

But this code does not work:

onStepChanging: function (event, currentIndex, newIndex) {
    fetch('/validate?username='  + $('#username').val())
    .then(function(result) {
        if (result == 'valid') {
            return true;
        }
        return false;
    });
}

This second code does not work, because it does not wait for the result of the fetch method.

How can I force it to wait for the result of fetch, and then return?

Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
Ali EXE
  • 853
  • 1
  • 7
  • 21
  • 1
    Look at [the Issues page for the "jQuery-steps" repository on Github](https://github.com/rstaib/jquery-steps/issues) -- there are multiple issues which call for solutions to the same problem you're having -- being able to have the framework wait on results of asynchronous operations (e.g. `fetch`). The trouble with async. programming in JavaScript is that the entire call stack has to be aware that there is an asyncronous operation that may be going on somewhere down the stack, and wait accordingly. If whatever calls `onStepChanging` does not do that, you will need to try another way. – Armen Michaeli Oct 28 '21 at 10:31
  • This comment might give you somewhat of a workaround: https://github.com/rstaib/jquery-steps/issues/185#issuecomment-361055520, the key part is to use `$("#wizard").steps("next");` in the callback to progress (although, I believe this will show your form as invalid while the async operation is occurring) - See also: [jQuery wizard steps move before ajax call completed](https://stackoverflow.com/a/41667561) – Nick Parsons Oct 28 '21 at 10:42
  • What about [async/await](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Asynchronous/Async_await)? – Peter Krebs Oct 28 '21 at 11:04
  • @PeterKrebs to use `await` the `onStepChanging` would need to be `async`, so the `onStepChanging` would end up returning a Promise that resolves to the returned boolean as all `async` functions return Promises (event if one isn't explicitly returned) – Nick Parsons Oct 28 '21 at 11:42
  • @NickParsons Oh it cannot work with promises at all? Then the `fetch()` must be called in advance. None of the code within `onStepChanging` uses the function parameters. So it could be called at any time and be async there. – Peter Krebs Oct 28 '21 at 12:25

0 Answers0