Personally, I like to do something like this as Error Reporting. When something goes wrong – in the PHP function – set an Error Header that will return back to your JQuery along with a string message:
header( 'HTTP/1.1 400 Empty Attachment' );
echo 'Could Not Upload File.';
exit;
To classify this as an error
header you need HTTP/1.1 400
but after that you may put any kind of text. Here’s a list of response codes. Then on your $.ajax().fail()
function you can display those errors in a meaningful way:
$.ajax( {
url: '/wp-admin/admin-ajax.php',
type: 'POST',
data: {
action : 'your_function_hook_thing',
some_data : some_kind_of_data
},
dataType: 'text'
} )
.success( function( data ) {
/* You win! */
} )
.fail( function( data ) {
/* You lose, show error */
console.log( data.responseText );
console.log( 'Request failed: ' + data.statusText );
} );
The data.responseText
is what you echo and the data.StatusText
is going to be what you decided to add into the header()
function in PHP.