2

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 :)

  • 1
    This is useful reading: https://stackoverflow.com/questions/6265814/how-to-trigger-jquery-ajax-error-callback-based-on-server-response-not-http-5 – IncredibleHat Dec 10 '17 at 21:06
  • Just put a syntax error in your php file. –  Dec 10 '17 at 21:09
  • Both of top comments are OK + you can use header('HTTP/1.1 500 OK'); in your PHP with any code except 200. See codes here: http://php.net/manual/en/function.http-response-code.php#107261 – iazaran Dec 10 '17 at 21:13

2 Answers2

7

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.

Christian Santos
  • 5,386
  • 1
  • 18
  • 24
0

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

Ben in CA
  • 688
  • 8
  • 22