WordPress: changing the status code on AJAX response

Use the following code in WordPress for changing the HTTP status code returned from an AJAX call, e.g. setting a 400 – Bad Request error:

function my_ajax() {
  status_header(400);
  echo 'Some return message';
  wp_die();
}
add_action( 'wp_ajax_my_ajax', 'my_ajax' );

Where status_header and wp_die are two WordPress’s functions.

NOTE: be sure to set the status header before any echo statement, otherwise a 200 status code is always returned and you will get this error/warning:

Warning: Cannot modify header information - headers already sent by (output started at /some/path/to/your/php/file.php:232) in /some/path/to/your/php/file.php on line 292

Hint

Set display_errors: Off inside your php.ini file, otherwise if you have a PHP error will be returned a 200 status code and not an error code as you might expect (see here the why).

References

https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_%28action%29
https://codex.wordpress.org/Function_Reference/status_header
https://codex.wordpress.org/Function_Reference/wp_die

Categories

Category BootstrapCategory CoffeescriptCategory DrupalCategory GravCategory HTMLCategory JavascriptCategory JoomlaCategory jQueryCategory LaravelCategory MagentoCategory PHPCategory SharePointCategory SpringCategory ThymeleafCategory WordPressCategory Workflow

Comments

Developed and designed by Netgloo
© 2019 Netgloo