Server throws exception, client misunderstands success

I code simple login / registration functions using jQuery, PHP, and PostgreSQL. The following code is from a PHP file that deals with inputs. It throws an exception when the login / password combination is incorrect.

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

$query = "SELECT * FROM users WHERE username='$username' AND password='$password'";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
$numResults = pg_num_rows($result);

if ($numResults == 0) {
  throw new Exception("Incorrect combination of username and password.");
  //die('Incorrect combination of username and password.');
}

However, on the client side in the jquery, the success function is executed even if the server throws an exception.

      $.ajax({
        type: "POST",
        url:"login.php",
        data: dataString,
        success: function() {
//THIS FUNCTION IS EXECUTED....
          $('#errorMsg').html('Login is successful!');
          $('#errorMsg').show();
          $('#usernameTxtBx').val("");
          $('#passwordTxtBx').val("");
        },
        error:function (xhr, ajaxOptions, thrownError){
          window.alert(xhr.status);
          window.alert(thrownError);
        }
      });
+5
source share
3 answers

First of all: Please take a look at SQL Injections because you are quite vulnerable ...;)

, HTTP , , PHP. - , :

function exception_handler($exception) {
    header("HTTP/1.1 400 Bad Request");
    echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');

, HTTP- . , jQuery .

400 Bad Request , , -, . , , , , , 500 .

( UserErrorException):

function exception_handler($exception) {
    if($exception instanceof UserErrorException) {
        header("HTTP/1.1 400 Bad Request");
    } else {
        header("HTTP/1.1 500 Internal Server Error");
    }
    echo "Uncaught exception: " , $exception->getMessage(), "\n";
}

set_exception_handler('exception_handler');
+4

PHP Javascript. . JS . . PHP HTTP, "200 OK", JS 200 ok-, , AJAX .

+3
+1

All Articles