最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Return http response code from PHP to AJAX - Stack Overflow

programmeradmin3浏览0评论

I am trying to make a login page for a website. I have a function that uses AJAX to send a request to a PHP script to check if the proper username and password has been entered in. I send http_response_code(200) if the the query returns a successful result, otherwise I send http_response_code(403). However, the login function seems to not return any response status. The response seems to be undefined. In this case, the function gives me the window alert for the wrong password or username even if the correct password and username is entered. What condition should I be checking to determine what the success function should do based on the http response code? Is there another way to return a condition to AJAX based on what the PHP script does?

Here it the code for the login function.

function login(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var dataString = 'username1=' + username + '&password1=' + password;
if (username == '' || login == ''){
    window.alert("Please fill in username or password.");
}
else{
    $.ajax({
        type: "POST",
        url: "login.php",
        data: dataString,
        cache: false,
        crossDomain : true,
        success: function(response) {
            if (response.status == 200) {
                window.location = 'http://localhost/site.html';
            }
            else {
                window.alert("The password or username you have entered is not valid");
            }
        }
    });
}        
return false;

}

Here is my php script.

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$password2 = $_POST['password1'];
$username2 = $_POST['username1'];
$connection = mysqli_connect("localhost", "root", "password", "database") or die("Unable to connect to MySQL");  
$query = mysqli_query($connection, "SELECT * FROM users where username = '$username2' AND password = '$password2'") or die(mysqli_error($connection));
$row = mysqli_fetch_array($query, MYSQLI_BOTH) or die(mysqli_error($connection));
if(!empty($row['username']) AND !empty($row['password'])) {
    session_start();
    $_SESSION['username'] = $username2;
    http_response_code(200);
    echo "Successful Login";
    exit;
}
else{
    http_response_code(403);
    echo "The password or username you have entered is not valid";
}
mysqli_close($connection);
?>

I am trying to make a login page for a website. I have a function that uses AJAX to send a request to a PHP script to check if the proper username and password has been entered in. I send http_response_code(200) if the the query returns a successful result, otherwise I send http_response_code(403). However, the login function seems to not return any response status. The response seems to be undefined. In this case, the function gives me the window alert for the wrong password or username even if the correct password and username is entered. What condition should I be checking to determine what the success function should do based on the http response code? Is there another way to return a condition to AJAX based on what the PHP script does?

Here it the code for the login function.

function login(){
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
var dataString = 'username1=' + username + '&password1=' + password;
if (username == '' || login == ''){
    window.alert("Please fill in username or password.");
}
else{
    $.ajax({
        type: "POST",
        url: "login.php",
        data: dataString,
        cache: false,
        crossDomain : true,
        success: function(response) {
            if (response.status == 200) {
                window.location = 'http://localhost/site.html';
            }
            else {
                window.alert("The password or username you have entered is not valid");
            }
        }
    });
}        
return false;

}

Here is my php script.

<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');
$password2 = $_POST['password1'];
$username2 = $_POST['username1'];
$connection = mysqli_connect("localhost", "root", "password", "database") or die("Unable to connect to MySQL");  
$query = mysqli_query($connection, "SELECT * FROM users where username = '$username2' AND password = '$password2'") or die(mysqli_error($connection));
$row = mysqli_fetch_array($query, MYSQLI_BOTH) or die(mysqli_error($connection));
if(!empty($row['username']) AND !empty($row['password'])) {
    session_start();
    $_SESSION['username'] = $username2;
    http_response_code(200);
    echo "Successful Login";
    exit;
}
else{
    http_response_code(403);
    echo "The password or username you have entered is not valid";
}
mysqli_close($connection);
?>
Share Improve this question edited Apr 2, 2018 at 2:20 Spechal 2,7166 gold badges34 silver badges50 bronze badges asked Apr 2, 2018 at 2:12 yehrayyehray 31 gold badge1 silver badge3 bronze badges 6
  • 1 You mean "return", right? – yaakov Commented Apr 2, 2018 at 2:14
  • 2 Please use PDO or something that does prepared statements for you. You're code is vulnerable to SQL injection. – Spechal Commented Apr 2, 2018 at 2:16
  • response is not an object/array... That's not how you would check the response.status – sam Commented Apr 2, 2018 at 2:17
  • change var dataString = 'username1=' + username + '&password1=' + password; to var dataString = {username1 : username,password1:password}; – Barclick Flores Velasquez Commented Apr 2, 2018 at 2:17
  • 1 I don't think a 403 response will ever trigger ajax's success function and you had better add a fail handler, or look at the statusCode property to build custom handlers for various response codes. – James Commented Apr 2, 2018 at 2:28
 |  Show 1 more ment

2 Answers 2

Reset to default 5

When you check for the response and send the get response.status you do do not actually have an array or object as a response in your hands:

So when checking for the login you can create an array with status and a message and json_encode() it so you javascript code can pick it up and read it.

<?php
// fix your query connection - you are currently vulnerable. It does go outside of the scope of your question so I am not going to tackle it here.
if(!empty($row['username']) AND !empty($row['password'])) {
    session_start();
    $_SESSION['username'] = $username2;
    $return = array(
        'status' => 200,
        'message' => "Login Successful."
    );
    http_response_code(200);
}
else{
    $return = array(
        'status' => 403,
        'message' => "Login attempt denied."
    );
    http_response_code(403);
}
print_r(json_encode($return));

Now you can get the response back in your AJAX function:

    success: function(response) {
        var data = $.parseJSON(response);
        if (data.status == 200) {
            window.location = 'http://localhost/site.html';
        }
        else {
            window.alert(data.message);
        }
    }

The response argument that you are using in the success function is the returned data from the AJAX call, not the status and/or headers. You can get a string describing the status by getting the second argument to the function:

$.ajax({
  ...
  success: function(data, status){
    if(status == "success"){
      // success code.
    }
  }
});

View the jQuery.ajax docs for more information.

发布评论

评论列表(0)

  1. 暂无评论