1

My form onSubmit is calling:

onsubmit="validate(this); return false;"

validate() is as follows:

function validate(obj) {
    $.ajax({
        url : "ajax/validate_check.php",
        type : "POST",
        data : $("#" + obj.id).serialize(),
        success : function(data) {
            $('#' + obj.id + ' :input.form_errors').removeClass('form_errors')
            data = $.parseJSON(data);
            if(data['error_count'] >= 1) {
                $.each(data, function(i, item) {
                    $('#' + i).addClass('form_errors');
                });
            } else {
                $('#' + obj.id).submit();
            }
        }
    });
}

When I have 0 errors it's trying to submit the form but I'm getting an infinite loop. I realize it's happening because my onSubmit calls the function again. How do I actually submit the form when I'm ready? What is the proper way to approach this?

SeanWM
  • 16,789
  • 7
  • 51
  • 83

2 Answers2

1

Your validate function should return either true or false depending on errors.

  onsubmit = "return validate(this)"

  function validate(obj){
     ...
     if(data['error_count'] >= 1) {
            $.each(data, function(i, item) {
                $('#' + i).addClass('form_errors');
            });
            return false; //stop submitting
        } else {
            return true;//continue submitting
        }
  }

Although, since you are using jquery:

     $("#formid").submit(function(){
           //your validation code
     });

may be better.

Check out this page for more details. There is a good example.

Vincent Ramdhanie
  • 102,349
  • 23
  • 137
  • 192
0

You are already submitting the form for validation.

On } else { you can't submit it again, as you noticed. You should call a function to submit it to whatever_process_the_validated_data.php

Though I'd suggest having the same .php to validate and process data - a class or function to each. That way you can:

$('.forms_that_need_validation').submit(function() {
$.ajax({
    url : "ajax/data_validation_and_processing.php",
    type : "POST",
    data : $(this).serialize(),
    success : function(data) {
        $(this + ' :input.form_errors').removeClass('form_errors')
        data = $.parseJSON(data);
        if(data['error_count'] >= 1) {
            $.each(data, function(i, item) {
                $('#' + i).addClass('form_errors');
            });
        } else {
            location.reload();
        }
    }
});
return false;
});

What happens is, if the data fails to be validated, it returns an error - you should code you .php in order not to process the data if it's not validated. Otherwise, the data was validated and processed already, then it just reloads the page.

Alex
  • 1,416
  • 4
  • 16
  • 42