REST API – How to send custom HTTP-Status?
-
Hi,
I’m currently working on a plugin.
I make Ajax-Calls through build-in REST API. I don’t use the extra REST API plugin, but I don’t know where to post my request.My JS makes an Ajax-call (POST) to the REST API route and my custom PHP-script is processing the request.
My PHP-script fetches data from the database and sends it back to the browser.Its working fine, but I want to implement some better error-handling.
Is it possible to send a custom HTTP-Status to the browser?
For example if my sql-query doesn’t return any data, I want to send a useable HTTP-Status code.I have registered the following route, which calls the function “ajax_Interface”:
register_rest_route( 'blabla/v1', '/ajax-interface', array( 'methods' => WP_REST_Server::CREATABLE, 'callback' => array( $this,'ajax_interface' ), 'permission_callback' => function () { return current_user_can( 'administrator' ); } ));The function “ajax_interface” does some work. For example I do a SQL-update …
function ajax_interface() { // DB Query $db_update_result = $wpdb->update( ... SQL update ... if ( $db_update_result > 0) { error! - Give error status code back to JS } else { success! } return ( $ajax_callback_array ); }If the SQL-update is not OK it should give a status code back. I want to react on error with JS:
error: function(data) { // if error occured }I tried it for example with the status_header() function, but this doesn’t work.
How it has to be done?Thank you
The topic ‘REST API – How to send custom HTTP-Status?’ is closed to new replies.