I have the following function in a project im working on and everything up to now works well apart from im stuck with showing error message in alert popup when the function die.
This is Ajax Script
jQuery(window).load(function() {
action = jQuery.QueryString["action"];
collection_id = jQuery.QueryString["cc"];
current_userid = jQuery.QueryString["cu"];
user_name = jQuery.QueryString["su"];
collection_name = jQuery.QueryString["cn"];
cbcolor = jQuery.QueryString["ccol"];
permission = jQuery.QueryString["permission"];
if(action == 'sharecookbook' && jQuery('body').hasClass('logged-in')) {
new jQuery.flavr({
content : 'Do you really want to add this collection?',
dialog : 'confirm',
onConfirm : function(){
jQuery.ajax({
url: wpb_ajax_url,
data: 'action=wpb_sharecollection&collection_id='+collection_id+'¤t_userid='+current_userid+'&user_name='+user_name+'&collection_name='+collection_name+'&cbcolor='+cbcolor+'&permission='+permission+'&nonce='+ajax_object.nonce,
dataType: 'JSON',
type: 'POST',
success:function(data){
window.location = "/";
}
});
},
});
}
});
Then the following is the ajax php funtion
/* share new collection */
add_action('wp_ajax_nopriv_wpb_sharecollection', 'wpb_sharecollection');
add_action('wp_ajax_wpb_sharecollection', 'wpb_sharecollection');
function wpb_sharecollection(){
global $wpb;
$output = '';
extract($_POST);
check_ajax_referer( 'ajax_form_nonce', 'nonce' );
$wpb->share_collection( $current_userid,$collection_id,$collection_name,$cbcolor,$user_name,$permission );
wp_send_json ( $output );
}
And the following is the share collection function defined in above php funtion
/* Share collection */
function share_collection($uid,$id,$name,$cbcolor,$user,$permission) {
$cbcolor = str_replace(" ", "#", $cbcolor);
$type = 'shared';
$user_id = get_user_by( 'email', $user );
$collections = $this->get_collections($user_id->ID);
$collectionsdata = $this->get_collectionsdata($user_id->ID);
$collectionsdataoriginal = $this->get_collectionsdata($uid);
$collectionsdatashared = $this->get_collectionsdatashared($uid);
foreach($collectionsdata as $j => $ajj) {
if ( isset($ajj['parent']) && $ajj['parent'] == $id && isset($ajj['owner']) && $ajj['owner'] == $uid ) {
wp_die( 'This is an error', 'Error' );
}
}
$collections[] = array();
$collectionsdata[] = array('label' => $name,'cbcolor' => $cbcolor,'owner' => $uid,'parent'=>$id,'type' => $type,'permission' => $permission);
$collectionsdataoriginal[$id] = array('label' => $name,'cbcolor' => $cbcolor,'owner' => $uid,'type' => $type);
$idx = count($collectionsdata) - 1;
$collectionsdatashared[] = array('myid'=>$id,'suser' => $user_id->ID,'child'=>$idx);
update_user_meta($user_id->ID, '_wpb_collections', $collections);
update_user_meta($user_id->ID, '_wpb_collectionsdata', $collectionsdata);
update_user_meta($uid, '_wpb_collectionsdata', $collectionsdataoriginal);
update_user_meta($uid, '_wpb_collectionsdatashared', $collectionsdatashared);
}
In the last code you can see there is wp_die defined with error message. I need to alert this when the function dies to the user. Can you suggest a way to do this.
Thanks in advance
Codex says that wp_die() function returns 500 HTML status code. In that case if the request fails use qXHR.fail()
method ( or error callback, although is deprecated ), to catch error:
$.ajax({ /* options */ })
.done( function( data, textStatus, jqXHR ) {
alert( "success" );
})
.fail( function( jqXHR, textStatus, errorThrown ) {
alert( "error" );
});
EDIT:
I've done some testing and wp_die()
returns 500 status, but not for ajax calls. For ajax it just prints response message and die. Here are few scenarios.
Calling wp_die()
with plain string message
wp_die( 'Error message', 'Error' );
Status code is 200, but jQuery calls .fail()
callback with parsererror
message. jQuery expects json
( not text/html
that wp_die()
returns ) as defined in datatype
option. If you remove datatype option, jQuery will try to guess the data type based on the MIME type of the response. wp_send_json()
sets the Content-Type of the response to application/json
.
Calling wp_die()
with json data, or calling wp_send_json()
wp_die( wp_json_encode( array( 'status' => 'error', 'message' => 'Error message' ) ) ); // text/html;
wp_send_json( array( 'status' => 'success', 'data' => 'output' ) ); // application/json
.done()
callback is invoked and json data are passed, the only difference is that later function sets the Content-Type to application/json
, but jQuery will try to parse both responses as json since the datatype option is set to json.
Configure Wordpress to send 500 status for ajax requests
Wordpress can be configured to send 500 status for ajax requests with wp_die_ajax_handler
filter.
// example: wp_die( 'Error message', 'Error', 500 );
add_filter( 'wp_die_ajax_handler', function( $handler ) {
return function( $message, $title, $args ) use ( $handler ) {
if ( isset( $args['response'] ) && $args['response'] == 500 ) {
header( "HTTP/1.1 500 $title" );
die( $message );
}
$handler( $message );
};
});
Solution without wp_die()
functions
Simple way without wp_die()
would be to set the success property in json response, and to check that property in .done() callback.
// php
wp_send_json( array( 'success' => true, 'data' => 'output' ) ); // for success
wp_send_json( array( 'success' => false, 'data' => 'Error message' ) ); // for failure
// js
jqXHR.done( function( data )
{
if ( data.success ) console.log( data.data );
if ( !data.success ) console.log( data.data );
});
wp_send_json_error()
function
The above is implemented in Wordpress with wp_send_json_error()
function.
// sets a JSON response as array( 'success' => false, 'data' => 'Error message' ), then calls wp_send_json() and wp_die().
wp_send_json_error( 'Error message' );