Jhonatan Sandoval
Jhonatan Sandoval

Reputation: 1293

Validate a form using AJAX, then submit it

I'm validating a form using AJAX like this:

<script>

        $(function() {

            $("#loginForm").submit(function() {
               var data = $("#loginForm :input").serialize();
               var curl = "../view/index_valid.php";
               $.ajax({
                  url: curl,
                  method: "post",
                  data: data,
                  success: function(data) {
                      if(data==="logged") {
                          return true;
                      } else {
                          return false;
                      }
                  }

               });
               return false;
            }); // end loginForm submit function

        }); // end function

</script>

I think when the return is true, the form should submit (action="...")... but nothing happens. What could be wrong?

Upvotes: 0

Views: 608

Answers (1)

A. Wolff
A. Wolff

Reputation: 74420

Instead of return true; in success callback, submit the FORM using DOM node method:

$("#loginForm").submit(function () {
    var data = $("#loginForm :input").serialize();
    var curl = "../view/index_valid.php";
    $.ajax({
        context: this, //>> set context
        url: curl,
        method: "post",
        data: data,
        success: function (data) {
            if (data === "logged") {
                this.submit(); //>> that will submit the FORM
            } /*else {
                return false; //>> returning false here is useless
            }*/
        }
        return false;
    });
}); // end loginForm submit function

Upvotes: 1

Related Questions