简体   繁体   中英

Reading a response in Ajax php and mysql

I can't get the code to work and redirect to 2 different pages depending if the information is correct or not...

So far I have this on my login page:

$(function () {
$('#form').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: 'newfile.php',
        data: $('#form').serialize(),
        success: function (response){
        alert(response); 
                    if (success.text="Username or Password incorrect")
                        window.location.href = "index.php"; 
                    else if (success.text="login successful") {
                        window.location.href = "login_success.html";
                    } else {  
                    }
            }
        })
})

and the information Im reading from is (from another page):

<?php    
// Create connection
$conn = new mysqli($servername, $username, $password, $database);

// Check connection
if ($conn->connect_error) {
     die(" Connection failed: " . $conn->connect_error);
} else {
echo "Connected successfully";
}
$sql="SELECT myusername, mypassword FROM user WHERE myusername = '" . mysqli_real_escape_string($conn, $myusername) . "' and mypassword = '" . mysqli_real_escape_string($conn, $mypassword) . "';";
$result = $conn->query($sql);
if ($result->num_rows >0) {
    echo "login successful";
} else {
    echo "Username or Password incorrect";
}
$conn->close();

?> 

I hope this will work for you try this:

if (response=="usernames or Password incorrect") {
    window.location.href = "index.php";
} 
else if (response=="login successful") 
{
    window.location.href = "login_success.html";
 } 
else { }

Use this code in ajax success. Actually you are using simple ECHO in PHP and using response.text in ajax success.

UPDATE:

you are using = sign for comparing it should be == operator for compare.

UPDATE 2:

i suggest to use status as true false not long string in php like:

if ($result->num_rows >0) {
    echo true;
} else {
    echo false;
}

Than in ajax response:

if(response == true){
// Success url
}
else {
// failure url
}

The variable success will be undefined inside the success callback function. So the next line will not be executed. So the page will not be redirected. According to your php code , you need to check if response is equal to the corresponding result of not.

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