0

I'm trying to connect to my database via PHP when my ajax request is executing (for a post method), but I want to show my user an error message if it is unable to connect. I can show the success message when it does connect but I'm wondering if there is a way to manually throw the catch block so that I know my code is working and will display a message to the user if the user is unable to connect to the database (currently using console.log for testing purposes).

JS

$.ajax({
  type: "post",
  url: "test.php",
  dataType: "json",
  error: function(data) {
    console.log(data.status);
    console.log("Not Successful Test");
    if (data.status == "connectionError") {
      console.log("Didn't connect to database");
    } else {
      console.log("Other");
    }
  },
  success: function(data) {
    console.log(data.status);
    console.log("Successful Test");
    if (data.status == "success") {
      console.log("Connected to Database");
    } else {
      console.log("Other");
    }
  }
});

test.php

try {
    require_once("dbConn.php");
    $dbConn = getConnection();
    $response_array["status"] = "success";
} catch (Exception $e) {
    $response_array["status"] = "connectionError"; // Want to display this response in JS code
}

header("Content-type: application/json");
echo json_encode($response_array);

dbConn.php

function getConnection()
{
    try {
        $conn = new PDO(
            "localhost=localhost;dbname=dbname",
            "username",
            "password"
        );
        $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        return $conn;
    } catch (Exception $e) {
        throw new Exception("Connection error " . $e->getMessage(), 0, $e);
    }
}

SOLUTION test.php

try {
    require_once("dbConn.php");
    $dbConn = getConnection();
    $response_array["status"] = "success";
} catch (Exception $e) {
    // Added http response code then die() with message
    http_response_code(503);
    die("<b>Server Error.</b><br/> This service is currently unavailable. Please try again at a later time.");
}

header("Content-type: application/json");
echo json_encode($response_array);

then in JS

$.ajax({
  type: "post",
  url: "test.php",
  dataType: "json",
  error: function(data) {
    console.log(data.responseText);
  },
  success: function(data) {
    console.log(data.status);
    console.log("Successful Test");
    if (data.status == "success") {
      console.log("Connected to Database");
    } else {
      console.log("Other");
    }
  }
});
5
  • 1
    Look into the Dev-Console of your browser, it'll contain HTTP 200 all the time...If you want to use the "error" function in JS-Ajax, you'd have to send a HTTP code != 200. Commented Mar 10, 2020 at 18:53
  • Sorry but could you expand on this? I'm not sure what you mean Commented Mar 10, 2020 at 19:04
  • The AJAX handler for "success" and "error" are triggered by HTTP status code. So, no matter if your PHP script can make a DB connection or not, you send a valid answer (with HTTP status 200). Commented Mar 10, 2020 at 19:10
  • Does that mean it's not possible to get an error message for when the user can't connect to the database as the handler responds with a valid status code? Commented Mar 10, 2020 at 19:24
  • Sure it is, but as I said: you'll have to sent HTTP status code of 4xx to trigger the "error" method in your AJAX handler. See list of HTTP status codes: en.wikipedia.org/wiki/List_of_HTTP_status_codes Commented Mar 10, 2020 at 19:27

1 Answer 1

1

In order to inform the browser that the request has not succeeded, you need to pass a http response code that is not 2xx. For your purpose, you could use e.g. 503.

http_response_code(503);

That will ensure the browser's understanding that the output from the call is not a success (as it would be suggested by the default value of this, i.e. 200).

Following that statement, you can still return some JSON if you want the error messaging to be driven by the PHP layer.

Sign up to request clarification or add additional context in comments.

2 Comments

I tried to add the following code into the catch block in test.php but I'm still receiving a response code of 200 even though I have deleted the dbConn.php file from my web server
What you're probably seeing is PHP outputting some debug information due to the missing file. You need to use your browser's developer console to see what went wrong. In Chrome, do ctrl+shift+i, ten go networking tab, and select XHR section. Then fire up your Ajax request; you will see it show up there along with the response code (check Preview tab after selecting your request if you want to see what exactly PHP returned).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.