Tags
Asked 3 years ago
8 Jul 2021
Views 428
Harmony

Harmony posted

Return http response code from PHP to AJAX

Return http response code from PHP to AJAX
web-api

web-api
answered May 4 '23 00:00

In PHP, you can use the http_response_code() function to set the HTTP response code for your script. Here's an example:


http_response_code(404);

In this example, we set the HTTP response code to 404 (Not Found). You can set any valid HTTP response code using this function.

To return the HTTP response code to AJAX, you can use the status parameter of the $.ajax() function in jQuery. Here's an example:


$.ajax({
    url: "my_script.php",
    success: function(data, status, xhr) {
        // handle successful response
    },
    error: function(xhr, status, error) {
        // handle error response
        var httpStatus = xhr.status;
        alert("HTTP response code: " + httpStatus);
    }
});

In this example, we use the error callback to handle the response when the server returns an error. Inside the error callback, we get the HTTP response code from the status parameter of the xhr object, which contains the XMLHttpRequest object for the request.

We can then display the HTTP response code in an alert box or use it to handle the error response as needed.

Post Answer