0

I'm trying to validate a form by using an external API for email validating.

Here is my form tag :

<form class="form-horizontal" role="form" onsubmit="return validateForm()"  method="post">  

This is my JS code:

function validateForm() {
    var email = $("#email").val();
    $.ajax({
        url: "https://bpi.briteverify.com/emails.json?address=" +  $("#email").val() + "&apikey=XXXXXXXXXXX",
        dataType: "jsonp"
    }).then(function(data) {
        console.log('BrightVerify result : ' + data.status);
        if (data.status == 'invalid') {
            document.getElementById("checkResult").innerHTML = 'Email address is invalid!';
            console.log('Setting result to false.');
            return false;
        } 
    }); 
} 

No matter what the API returns, the form is submitted.

What am I missing?

  • 2
    Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – Andreas May 30 '16 at 11:53
  • you are making an ajax call that why – Ranjit Singh May 30 '16 at 11:53

2 Answers2

1

return false will prevent the form from getting submitted.

<form class="form-horizontal" role="form" onsubmit="event.preventDefault(); validateForm(); return false;"  method="post">

In your then method, you may call $(".form-horizontal").submit(); so that the form is submitted after the ajax call succeeds.

Chintan
  • 773
  • 9
  • 18
-1

validateForm function should looks like this:

function validateForm(event) {
    event.preventDefault();
    // ...
}

and instead of onsubmit="return validateForm()" use onsubmit="return validateForm(event)".

Form doesn't wait for ajax request and send data immediately. To stop this you should prevent default behaviour.

Paul Rumkin
  • 6,737
  • 2
  • 25
  • 35