How to send an error response from php to a jQuery Ajax post request

Good Evening!

First of all this is my First Question so sorry, i might be a little nervous.

I have a Problem in the following situation...

I have an ajax call like this:

$.ajax({
    url: "test.php",
    method: "POST",
    data: {
        "somedata": "somedata"
    },
    success: function(){
       //Do something when it is an success
    },
    error: function(){
       //Do something when it is an error
    }
});

Now i want to give in the test.php an error response so that the jQuery ajax call executes the error and not the success call even if there is no error.

Please don't answer like: 'Why would you like to do this?'
I just want to know if that's possible :)

Upvotes: 2

Views: 2784

Answers (2)

Ben in CA
Ben in CA

Reputation: 851

For anyone else looking at this, if you want a conditional method of checking for an AJAX error, check out this post:

https://stackoverflow.com/a/55201895/3622569

Upvotes: 0

Christian Santos
Christian Santos

Reputation: 5456

To manually set a response code within your php file, you can use http_response_code:

<?php
    http_response_code(500);
?>

See a full list of supported http response codes here (a comment from the docs).

As long as your server returns a response code in the range 4xx -5xx, your $.ajax error function will run.

Upvotes: 7

Related Questions