Validate and submit the form without participating in an endless loop?

I have an infinite loop using this jquery code, I know WHY, but I don't know HOW to fix this:

<form id="submitme"> <input value="" name="n1" id="n1" type="text"/> <input value="Send" type="button"/> </form> <script> $('#submitme').bind( 'submit', function() { $.post( 'validate.php', 'value=' + $('#n1').val(), function (data) { if (data == "true") $('#submitme').submit(); }); }); </script> 
+7
source share
3 answers

The jQuery.validate plugin will take care of this, and I highly recommend you use it:

 $('#submitme').validate({ rules: { n1: { remote: { url: 'validate.php', type: 'post' } } } }); 

But if you do not want to use it, another possibility is to use a global variable, for example:

 $('#submitme').submit(function() { if (!$.formSubmitting) { var $form = $(this); $.post('validate.php', { value: $('#n1').val() }, function (data) { if (data == 'true') { // set the global variable to true so that we don't enter // the infinite loop and directly submit the form $.formSubmitting = true; $form.submit(); } }); return false; } return true; }); 

Just a note: the button that you placed inside the form is not a submit button, so clicking on it will not trigger the submit handler. You must do this with the submit button:

 <input value="Send" type="submit" /> 
+3
source

I am not a jQuery expert, but in Prototype, when you write an event handler for an action, and you do not stop the default action that will be executed after all of your callback functions have completed. Therefore, simply by flipping the if-else statement, you can avoid an infinite loop:

 $('#submitme').bind( 'submit', function(event) { $.post( 'validate.php', 'value=' + $('#n1').val(), function (data) { if (data != "true") // if validation has failed, prevent default action (submit) event.preventDefault(); }); // if default action was not prevented it will be executed }) 
0
source

I found this solution:

 <form id="submitme"> <input value="" name="n1" id="n1" type="text"/> <input value="Send" type="button"/> </form> <script> $('#submitme').bind( 'submit', function() { if ($.data( $('#submitme' ), 'validated')) return true; $.post( 'validate.php', 'value=' + $('#n1').val(), function (data) { if (data == "true") { $.data( $('#submitme'), 'validated', true ); $('#submitme').submit(); } }); return false; }); </script> 
0
source

All Articles