1

I have a form, and before it submits I want to check some of the input against a database. The idea: 1) submit form, 2) check values, 3) show error or actually submit the form. Example:

$(form).submit(function() {
  $.post('check.php', {
    values
  }, function(res) {
    // result I need before submitting form or showing an error
  });

  return false;
});

Now, it takes some time before I get the result (i.e. not instantly), so I put in the return false at the bottom, preventing the form to submit before I get the $.post results back and do something with it.

Problem: after I get the results from $.post, and everything turns out to be OK, how do I tell the script to go on with submitting the form? If I use submit() it'll just take it back to this check script, creating an endless loop.

3 Answers 3

1

You're essentially submitting the form twice, if you did it this way. That seems wasteful. Instead, just prevent the form submission, and handle the values asynchronously (as you already are). From the server, accept the data if it's good and reject it if it's not. There's no need to submit the form if you're already sending the data to the server to begin with. It's a bit redundant.

Sign up to request clarification or add additional context in comments.

2 Comments

Yes, good point. I want to use the normal post (not asynchronously) because the page needs to be reloaded afterwards. But I still want feedback before that happens. But like you say, that's redundant. I guess I might as well process the data asynchronously if there was no error, and afterwards reload the page from within jQuery — although that's never really my favorite thing to do.
I understand you dilemma, Alec. But refreshing a page seems to make more sense than sending the same data to a server twice :)
1

You can use a boolean flag for this:

var isValid = false;
$(form).submit(function() {
  if (isValid) return true;
  $.post('check.php', {
    values
  }, function(res) {
    if (res.valid) {
      isValid = true;
      $(form).submit();
    }
    // result I need before submitting form or showing an error
  });

  return false;
});

1 Comment

There's not much security in that.
1

Try replacing the submit button with a link that has an onclick. Submit the form programatically afterward. E.g.:

<a id="submit">Submit</a>

$($("a#submit").click(function() {
   $.post('check.php', {
          values
         }, function(res) {
               // result I need before submitting form or showing an error
         });
  if (condition) {
     $('[name=form_name]').submit();
  };
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.