Reputation: 95
I'm creating a user registration form for my website and am using ajax to handle server side process. My problem is the handling of the response from my php code. Upon execution of the server side, the possible responses from it can be success (registered user), database connect error, empty field(s) error or failure to execute sql query (input(s) already exist in a unique sql field e.g. username, email). I want to know how I'm able to get the correct response for each of these to display a message to the user. What I have:
JS
$.ajax({
type: "post",
url: "userRegistration.php",
data: {
firstname: firstname,
surname: surname,
email: email,
usernameSignup: username,
passwordSignup: password,
passwordConfirm: passwordConfirm
},
dataType: "json",
success: function(data) {
console.log(data.status);
if (data.status == "success") {
console.log("Registration was successful");
//Do success stuff
} else if (data.status == "error") {
console.log("Didn't Execute Query");
// Do error stuff
} else if (data.status == "connectionError") {
console.log("Failed to connect to database");
// Do error stuff
} else {
console.log("Empty fields");
// Do error stuff
}
});
PHP
<?php
// try catch statement to connect to database through getConnection() function in dbConn.php file
try {
// try to connect to database
require_once("dbConn.php");
$dbConn = getConnection();
} catch (Exception $e) {
// database connect error
//echo "A problem occured: " . $e->getMessage();
$response_array["status"] = "connectionError";
}
// Form validation for POST method to check fields are not empty
if (!empty($_POST['firstname'])) {
$firstname = filter_has_var(INPUT_POST, 'firstname') ? $_POST['firstname'] : null;
$firstname = trim($firstname);
} else {
echo "A first name must be entered.<br/>";
}
// Same validation for other fields
// If all the previous steps are valid and variables are set, try to run the SQL query to make new account.
if (!empty($firstname) && !empty($surname) && !empty($email) && !empty($usernameSignup) && !empty($passwordHash)) {
try {
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES ('$firstname', '$surname', '$email', 0, '$usernameSignup', '$passwordHash')";
$execute = $dbConn->exec($sqlQuery);
$response_array["status"] = "success";
} catch (PDOException $e) {
// failure to execute error
//echo $sqlQuery . "<br>" . $e->getMessage();
$response_array["status"] = "error";
}
} else {
// empty field(s) error
$response_array["status"] = "empty";
}
// send the response
header("Content-type: application/json");
echo json_encode($response_array);
exit;
The success status handler works correctly but I am unable to get the error status handler when I try to pass data into the database when it already exists or the empty status handler for empty fields. I also don't know of a way to check for the connectionError status handler. Any advice/suggestions to handle these responses would be appreciated.
Upvotes: 0
Views: 74
Reputation: 782489
When you detect an error, you need to skip all the rest of the code until sending the JSON response. E.g. if you get a connectionError
, you shouldn't then try to perform the query; that will get an error, and replace $response_array['status'] = 'connectionError'
with $response_array["status"] = "error"
, so you'll report the wrong type of error.
Also, form validation errors need to be returned in the JSON response, not echoed directly.
One way to accomplish this is to nest your try/catch
statements.
<?php
// try catch statement to connect to database through getConnection() function in dbConn.php file
try {
// try to connect to database
require_once("dbConn.php");
$dbConn = getConnection();
// Form validation for POST method to check fields are not empty
if (!empty($_POST['firstname'])) {
$firstname = filter_has_var(INPUT_POST, 'firstname') ? $_POST['firstname'] : null;
$firstname = trim($firstname);
} else {
$response_array["status"] = "validationError";
$response_array["message"] = "A first name must be entered.";
}
// Same validation for other fields
// If all the previous steps are valid and variables are set, try to run the SQL query to make new account.
if (!empty($firstname) && !empty($surname) && !empty($email) && !empty($usernameSignup) && !empty($passwordHash)) {
try {
$sqlQuery = "INSERT INTO GH_users (firstname, surname, email, accountConfirmed, username, passwordHash)
VALUES ('$firstname', '$surname', '$email', 0, '$usernameSignup', '$passwordHash')";
$execute = $dbConn->exec($sqlQuery);
$response_array["status"] = "success";
} catch (PDOException $e) {
// failure to execute error
//echo $sqlQuery . "<br>" . $e->getMessage();
$response_array["status"] = "error";
}
} else {
// empty field(s) error
$response_array["status"] = "empty";
}
} catch (Exception $e) {
// database connect error
//echo "A problem occured: " . $e->getMessage();
$response_array["status"] = "connectionError";
}
// send the response
header("Content-type: application/json");
echo json_encode($response_array);
exit;
Upvotes: 1