How do I return a proper success/error message for JQuery .ajax() using PHP?

To return a proper success/error message for jQuery.ajax() using PHP, you can do the following:

  1. In your PHP script, you can set the HTTP status code of the response to indicate whether the request was successful or not. For example, you can use the http_response_code() function to set the status code to 200 to indicate success, or 400 to indicate an error.

  2. In addition to the status code, you can also include a message in the response body to provide more information about the success or error. For example, you could return a JSON object with a message property that contains the success or error message.

Watch a course Learn object oriented PHP

Here's an example of how you might do this in PHP:

<?php

$success = true; // change this to false to return an error

if ($success) {
  // set the status code to 200 to indicate success
  http_response_code(200);

  // return a JSON object with a message property
  echo json_encode(array("message" => "The request was successful"));
} else {
  // set the status code to 400 to indicate an error
  http_response_code(400);

  // return a JSON object with a message property
  echo json_encode(array("message" => "There was an error processing the request"));
}

Then, in your jQuery.ajax() call, you can use the success and error callbacks to handle the response depending on the status code:

$.ajax({
  url: "your-php-script.php",
  success: function(data) {
    // the request was successful
    console.log(data.message);
  },
  error: function(xhr, status, error) {
    // there was an error
    console.log(xhr.responseJSON.message);
  }
});