WordPress AJAX response codes using status_header

As I’m relatively new to WordPress plugin development, I’m constantly searching around for the cleanest and most “WordPress way” to do things. One function that helps write cleaner AJAX call handlers is status_header(), to inform the caller when things go wrong:

add_action( 'wp_ajax_myajaxaction', 'my_ajax_handler' );

function my_ajax_handler() {
    if ( ! empty($_POST) and check_ajax_referer( 'mynonce', 'nonce' ) ) {

        if ( things_go_wrong ) {
            status_header( 500 );
            echo "some informative message or code";
        }

        // ...
    }
}

and in the javascript using success and failure functions rather than deconstructing response text:

var nonce = jQuery("input#nonce").val();

jQuery.ajax({
   type: "POST",
   url: ajaxurl,
   data: {
	   name: encodeURIComponent(tabName),
	   id: tabId,
	   mynonce: nonce,
	   action: 'myajaxaction'
         },
	 success: function(msg) {
               // Handle a successful call
	 },
	 error: function(v,msg) {
            // Handle the error, with the text in msg
         }
});

You could also output the headers manually, but this gives a nice clean way to do it.

Discussion Area - Leave a Comment