简体   繁体   中英

onsubmit not working with ajax mysql validation

I know there are lots of similar questions, but i've been unable to find one that solves my problem.

The thing is i want to check whether the user/password in my form exists against the mysql db, and i do so by calling a javascript function at form's onsubmit attribute that posts the input via AJAX to a php that checks it and echoes result back to the javascript function, which alerts the user and returns false or returns true so that the form submits.

HTML

<span id="error_message" style="color:#CC3300;font-size:15px" ></span><br/>
<form method="post" action="./includes/process_login.php" onsubmit="return validateForm()" name="login_form">
    <div>
        <label for="email">Email</label><br/>
        <input placeholder="Introduce tu email" type="text" id="email" name="email" maxlength="50" />
    </div>
    <div>
        <label for="password">Password</label><br/>
        <input placeholder="Introduce tu password" type="password" name="password" id="password" maxlength="16" />
    </div>
    <div>
        <a class="passwordReset" href="./admin/passwordRecovery.php">He olvidado mi contraseña...</a>
    </div>
    <input type="submit" id="submit_button" value="ENTRAR" />
</form>

JAVASCRIPT/AJAX

function validateForm() {
    var pattern = new RegExp(/* Email validation pattern */);
    var isValid;

    if (pattern.test($("#email").val())) {  
        $.ajax({
            url: "../includes/process_login.php",
            cache: false,
            type: "POST",
            data: "email=" + $("#email").val() + "&password=" + $("#password").val(),
            success: function(data){
                if (data == '1') {
                    isValid = true;
                } else {
                    $("#error_message").text('Email/Password incorrectos!CCC');
                    isValid = false;
                }
            },

            error: function(){
                $("#error_message").text('Email/Password incorrectos!');
                isValid = false;
            }
        });
} else {
    $("#error_message").text('El email debe tener un formato válido');
    isValid = false;

}

return isValid;
}

PHP both validation and form action:

<?php
include_once 'db_connect.php';
include_once 'functions.php';

sec_session_start();

if (isset($_POST['email'], $_POST['password'])) {
    $email = $_POST['email'];
    $password = $_POST['password'];

    if (login($email, $password, $mysqli) == true) {
        // Login success 
    header("Location: ../graficas.php");
        echo '1';
    } else {
        // Login failed 
    echo '0';
    }
} else {
    // The correct POST variables were not sent to this page.
    echo '0';
}

exit;

The form is ALWAYS submitted when the email input compells to email regex, so the problem must be inside the ajax function. But i can't figure out what it is, and after a few hours, i'm closer than ever to an asylum.

Thanks in advance!

Inside your validateForm() add this to prevent form submitting

e.preventDefault();

Like this

function validateForm(e){
  var pattern = new RegExp(/* Email validation pattern */);
  var isValid;
  if (pattern.test($("#email").val())) {  
   e.preventDefault();
   //Do rest of your code

I finally could get it done by putting both the form and all the logic in a single PHP file:

    <!-- The HTML login form -->
    <form method="post" action="<?=$_SERVER['PHP_SELF']?>">
        <div>
            <label for="username">Login</label><br/>
            <input placeholder="Introduce tu login" type="text" id="user" name="username" maxlength="50" />
        </div>
        <div>
            <label for="password">Password</label><br/>
            <input placeholder="Introduce tu password" type="password" name="password" id="password" maxlength="16" />
        </div>
        <div><a class="passwordReset" href="./admin/passwordRecovery.php">He olvidado mi contraseña...</a></div>
        <input type="submit" id="submit_button" name="submit" value="ENTRAR" />
    </form>

    <?php
    if (isset($_POST['submit'])){
        include_once 'includes/db_connect.php';
        include_once 'includes/functions.php'; 
        sec_session_start();

        $username = $_POST['username'];
        $password = $_POST['password'];     

            if (login($username, $password, $mysqli) == true) {
                // Login success
                echo '<script type="text/javascript">window.location.replace("graficas.php");</script>';

            } else {
                // Login failed
                echo '<script type="text/javascript">document.getElementById(\'error_message\').innerHTML = "Login/Password incorrectos!";</script>';
            }
    }
    ?>

Generating JS scripts via 'echo' when needed to modify elements and avoiding the AJAX issue.

The key element here is

isset($_POST['submit'])

to check whether the form has been previously submitted.

I took the idea from this nice tutorial: http://w3epic.com/php-mysql-login-system-a-super-simple-tutorial/

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