0

I have a login page, I want to check if the given email exists in the database with an AJAX request. If the email is not found, I want to stop the process so the form won't be submitted. check.php returns a string if the email is not found (otherwise, it doesn't return anything.) I call the preventDefault(); method when the check.php returns a string, but it doesn't stop the form from submitting data. How can I stop the submission of the form when the email doesn't exist? It should be something easy, but I can't figure it out.

$("form").submit(function(event) {
    $.ajax({
        url: "check.php",
        cache: false,
        type: "POST",
        data: {email: $(".email").val()},
        dataType: "text",
        success: function(info) {
          $(".info").text(info);
        },
        complete: function() {
          if (!$(".info").text() == "") {
            event.preventDefault();
          }
        }
    });
});
Balázs
  • 15
  • 2
  • 2
    You can't call `preventDefault()` inside an asynchronous callback; you can only stop the form submission immediately or not at all. – Mitya Sep 24 '18 at 18:13
  • You cannot do this. You need to cancel the event *before* the `submit` handler returns. Your `submit` handler cannot be asynchronous and still allow the form's default `submit` to proceed. – user229044 Sep 24 '18 at 18:14

0 Answers0