JLi_2398
JLi_2398

Reputation: 95

Ajax - Database Connection Handling

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");
    }
  }
});

Upvotes: 0

Views: 347

Answers (1)

Felan
Felan

Reputation: 93

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.

Upvotes: 1

Related Questions