I have a form with fields to connect to a database. This includes hostname, database, username and password. I am using an AJAX call to connect to the database. Some error handling needs to be taken care of, one of them is failing to connect to the database.
The exception is caught in a try-catch statement, I update the $result
variable with the error message. This is then returned to the AJAX call.
Here is a simplified version of the code:
AJAX Call:
$.ajax({
url: _url + 'dbv.php',
type: 'POST',
data: {
db_host: $('input[name="db_host"]').val(),
db_name: $('input[name="db_name"]').val(),
db_username: $('input[name="db_username"]').val(),
db_password: $('input[name="db_password"]').val(),
save_path: $('input[name="save_path"]').val()
},
dataType: 'json',
success: function(data) {
if (data.error) {
console.log('success (error): ' + JSON.stringify(data));
}
else {
console.log('success: ' + JSON.stringify(data));
}
},
error: function(data) {
console.log('error: ' + JSON.stringify(data));
}
});
PHP:
try {
if ($_POST['db_host'] && $_POST['db_username'] && $_POST['db_password'] && $_POST['db_name'] && $_POST['save_path']):
$host = $_POST['db_host'];
$user = $_POST['db_username'];
$password = $_POST['db_password'];
$database = $_POST['db_name'];
$path = $_POST['save_path'];
else:
throw new Exception('Empty Fields', '1');
endif;
if (!$result->error):
$conn = new mysqli($host, $user, $password, $database);
// ...
mysqli_close($conn);
endif;
}
catch (Exception $e) {
$result->error = true;
$result->message = 'Error: ' . $e->getMessage();
}
$result->message = (!$result->error) ? 'Successful' : $result->message;
echo json_encode($result);
The first exception in the code, Empty Fields
, is caught and returned to the success
function. The issue I'm having is that the error
AJAX state is fired not when the database connection is incorrect. The returned data includes both PHP's default error message and the $result
variable. Shouldn't this be just the $result
variable, same as the Empty Fields
Exception?
Screenshots of what's happening:
Error responseText including both PHP's error and $result
variable:
"responseText":
PHP's error:
"Warning: mysqli::mysqli(): php_network_getaddresses: getaddrinfo failed: No such host is known. in ____\dbv.php on line 35
$result
variable:{\"error\":true,\"message\":\"Error: php_network_getaddresses: getaddrinfo failed: No such host is known. \"}"
I've been searching quite a bit and it looks like the logic is fine - maybe there's something I'm completely missing.
Two examples similar to what I'm trying to do: https://stackoverflow.com/a/20938633/1275525, https://stackoverflow.com/a/12693587/1275525