Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validate and submit a form without enter in an infinite cycle?

I am having an infinite cycle using this jquery code, I know WHY but I dont 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>
like image 825
Cristian Avatar asked Jul 24 '11 09:07

Cristian


1 Answers

The jQuery.validate plugin takes care of this and I would strongly recommend you using it:

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

But if you don't want to use it another possibility is to use a global variable, like so:

$('#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 remark: the button you have placed inside the form is not a submit button so clicking it will not trigger the submit handler. You should make it a submit button:

<input value="Send" type="submit" /> 
like image 126
Darin Dimitrov Avatar answered Nov 15 '22 01:11

Darin Dimitrov