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