tags:

views:

84

answers:

3

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.

Any ideas? Thanks in advance and Merry Christmas!

+1  A: 

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;
});
jimyi
There's not much security in that.
Jonathan Sampson
+1  A: 

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.

Jonathan Sampson
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.
Alec
I understand you dilemma, Alec. But refreshing a page seems to make more sense than sending the same data to a server twice :)
Jonathan Sampson
+1  A: 

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();
  };
});
SapphireSun