php – Ajax Response Formatting-ThrowExceptions

Exception or error:

I have a user registration for my website, in which an ajax request is executed when the sign up button is clicked. This request handles validation, as well as adding the user to the database. I have everything working but I have a minor problem which I would like to fix. In my error handling, the response can return a 400 http status code with either a missing field or invalid field message. For these messages, I would like to have it so the sentence before the line break is displayed on one line, and then the sentence after the line break is displayed in a new line.

PHP:

// If all the previous steps are valid and variables are set, try to run the SQL query to make new account.
if (isset($firstname) && isset($surname) && isset($email) && isset($usernameSignup) && isset($passwordHash)) {
    try {
        // code to add user to database not included but is here
    } catch (PDOException $e) {
        http_response_code(400);
        die("Email or Username Already Exists.\n Make sure these fields are valid before trying again.");
    }
} else {
    http_response_code(400);
    die("Missing Field(s).\n Make sure there are no empty fields before trying again.");
}

JS:

$.ajax({
    type: "post",
    url: "userRegistration.php",
    data: {
    },
    dataType: "json",
    success: function(xhr) {
      // Success handler code
      }
    },
    error: function(xhr) {
      // Default error handler code
    },
    statusCode: {
      400: function(res) {
        console.log(res);
        console.log(res.status);
        console.log(res.responseText);
        $("#loadingIcon").addClass("d-none");
        $("#errorResponse").removeClass("d-none");
        $("#errorMessage").text("An error occured: " + res.responseText);
      }
    }
});

What it looks like now

I would like “Make sure there are no empty fields before trying again” to be on a new line. If possible, I would also like to get the “Missing Field(s)” in bold.

How to solve:

Add html tags to your text:

die("<b>Missing Field(s).</b><br /> Make sure there are no empty fields before trying again.");

Then change your js:

$("#errorMessage").html("An error occured:<br />" + res.responseText);

You need to use html() function, as your text contains html tags.

Leave a Reply

Your email address will not be published. Required fields are marked *