简体   繁体   中英

prevent login Form from submission (AJAX) when credentials dont match (return false not working)

This is my form:

 <form name="loginform" method="POST" action="login" onsubmit="return validateLogin()">            
<div>  User Name  :<input class="input" name="username" type="text" /> </div> 
<div> Password  :<input class="input" name="password" type="password" /> </div>        
<div> id="yaha" style="color:red;font:bold 16px garamond"</div>                         
<input style="font-weight:bold;" type="submit" value="Login" />

javascript code is as shown:

function validateLogin()
{
var x1=document.forms["loginform"];
if(//validations)
      {
       return false;
      }
 else
{    goajax(x1.username.value,x1.password.value);}        
 }//validate login ends...

var requ = null;

function goajax( u,  p)
{
requ=new XMLHttpRequest();
//code for posting ajax data
requ.onreadystatechange=display;

} 
function display()
{
if(requ.readyState == 4)
{
    if(requ.status == 200)
    {
    var message = requ.responseText;
    alert("message==="+message);
    var x;
    if(message.trim() == "ok")
        {
        var x1=document.forms["loginform"];
        return true;
        }
        else if(message.trim() == "no")
        {
        document.getElementById('yaha').innerHTML="Invalid Username or Password!!!";
        x1.password.value="";
        return false;
        }
        else if(message.trim() == "nv")
        {
        document.getElementById('yaha').innerHTML="Account not Activated";
        return false;
        }
    }     
}

}

My question is : I am getting the responses from the server as desired but in case of undesired responses, the form is getting submitted even after "return false;" (see function display())

Please scroll down to function display() i don't want the form to be submitted when message is "no" or "nv". basically "return false" is not working

Another way is to cancel the default event (in this case the submit)

Like this:

function validateLogin(e)
{
var x1=document.forms["loginform"];
if(//validations)
      {
       e.preventDefault();
       return false;
      }

See: jQuery preventDefault();

Try posting with jQuery (If you are using it in the website)

I've been doing a lot of this in my current project using jQuery this way:

$('#form').submit(function () {

call_function_to_validate_and_submit(); return false;

});

Whenever I have a javascript error (syntax or other) the form gets submitted (like in a normal html form with no ajax) even if validation fails. My point is that you might have a syntax error somewhere in there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM