简体   繁体   中英

Login with POST Form, which trigger a javascript validation, and AJAX to a PHP file. Trouble storing data to PHP

Brief

I am now stuck at a part of AJAX, as I do now know how to extract the data out from the AJAX part and put into the PHP variables, so that I could access it and use it later. It also does not redirect me to another page (" Map.php ").

I tried looking online for the answers, but to no avail. Can anyone with experience please help. Also, I am not sure if my method of doing is correct, please let me know where I have done wrong.

In details

I want to do a " Login.php ", which will use a form to take the email and password from the user. There will be a "Login" button on the form which will trigger a javascript for the purpose of validation.

Upon validation, I will use AJAX to call another php file called " Auth.php ", which will have make a connection with a MySQL database, to search for that particular user verify the user.

The "Auth.php" will then return a json data of the user's particulars, which I intend to use in "Login.php" page, and to start a session with the $_SESSION[] variable of php. I also want the page to redirect the user to another page (" Map.php ") upon successful login.

Below are parts of my codes in the " Login.php " and " Auth.php ".

Login.php

<form name="myForm" action="Map.php" method="post" onsubmit="return validateForm()">
    <fieldset>
        <div class="form-group">
            <input class="form-control" placeholder="E-mail" name="email" type="email" autofocus value="<?php echo isset($_POST["email"])? $_POST["email"]: ""; ?>">
        </div>
        <div class="form-group">
            <input class="form-control" placeholder="Password" name="password" type="password" value="<?php echo isset($_POST["password"])? $_POST["password"]: ""; ?>">
        </div>
        <input type="submit" value="Login" class="btn btn-lg btn-success btn-block"/>
    </fieldset>
</form>

<script>
function validateForm() {
    //event.preventDefault();
    var email = document.forms["myForm"]["email"].value;
    var password = document.forms["myForm"]["password"].value;
    var re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;

    if (email == null || email == "") {
        alert("Email must be filled.");
        return false;
    }

    if (password == null || password == "") {
        alert("Password must be filled.");
        return false;
    }

    if(re.test(email)) {
        var data = {
            "email": email,
            "password": password
        };
        data = $(this).serialize() + "&" + $.param(data);
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "auth.php", 
            data: data,
            success: function(data) {
                alert("You have successfully logged in!");
                // TODO store user details in session
                return true; // return true to form, so will proceed to "Map.php"
            }
        });
        return false;
    }
    else {
        alert("You have entered an invalid email address!");
        return false;
    }
    return false;
}
</script>

Auth.php

$connection = mysqli_connect("localhost", "root", "", "bluesky");

// Test if connection succeeded
if(mysqli_connect_errno()) {
    die("Database connection failed: " . mysqli_connect_error() . " (" . mysqli_connect_errno() . ") " . 
    "<br>Please retry your last action. Please retry your last action. " . 
    "<br>If problem persist, please follow strictly to the instruction manual and restart the system.");
}

$valid=true;

if (isset($_GET['email']) && isset($_GET['password'])) {
    $email = addslashes($_GET['email']);
    $password = addslashes($_GET['password']);
} else {
    $valid = false;
    $arr=array('success'=>0,'message'=>"No username or password!");
    echo json_encode($arr);
}

if($valid == true){
    $query = "SELECT * FROM user WHERE email='$email' and password='$password'";
    $result = mysqli_query($connection, $query);
    if(mysqli_num_rows($result) == 1){
        $row = mysqli_fetch_assoc($result);
        $arr=array('success'=>1,'type'=>$row['type'],'user_id'=>$row['id'],'email'=>$row['email'],'name'=>$row['name'],'phone'=>$row['phone'],'notification'=>$row['notification']);
        echo json_encode($arr);
    }else{
        $arr=array('success'=>0,'message'=>"Login failed");
        echo json_encode($arr);
    }
}

// close the connection that was established with MySQL for the SQL Query
mysqli_close($connection);

Your ajax call should be like this:

data = $(this).serialize() + "&" + $.param(data)
$.post('auth.php', data, function(response){
  console.log(response);
});

you must use post method because you are getting password and email so its not a good practice. And for validation there is many jQuery plugins.

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