When I was trying to get multi-response from php shortcode function, I had the strange result with its Json output. In my php,
$result['success']=false;
$result['string']='You have not uploaded project file, please upload first!';
echo json_encode($result);
In js file
$.post(ajax_object.ajax_url, { //POST request
...............
}, function(data) { //callback
console.log(data);
alert(data);
});
But in my result, I got the
{"success":"true","string":"You have not uploaded project file, please upload first!"}0
I don't know why I got the number 0 at the behind of result.
When I was trying to get multi-response from php shortcode function, I had the strange result with its Json output. In my php,
$result['success']=false;
$result['string']='You have not uploaded project file, please upload first!';
echo json_encode($result);
In js file
$.post(ajax_object.ajax_url, { //POST request
...............
}, function(data) { //callback
console.log(data);
alert(data);
});
But in my result, I got the
{"success":"true","string":"You have not uploaded project file, please upload first!"}0
I don't know why I got the number 0 at the behind of result.
Share Improve this question asked Apr 14, 2020 at 2:29 CristianRCristianR 1413 bronze badges 2- Normally, shortcodes don't echo they return. I imagine we would need to see more code here. – Howdy_McGee ♦ Commented Apr 14, 2020 at 3:36
- Give full code details – Maidul Commented Apr 14, 2020 at 4:42
1 Answer
Reset to default 3As mentioned in the documentation:
When the handler has finished all of its tasks, it needs to die. If you are using the WP_Ajax_Response or wp_send_json* functions, this is automatically handled for you. If not, simply use the WordPress
wp_die()
function.wp_die(); // That's all folks!
So you either need to use:
$result['success'] = false;
$result['string'] = 'You have not uploaded project file, please upload first!';
echo json_encode( $result );
wp_die();
Or
$result['success'] = false;
$result['string'] = 'You have not uploaded project file, please upload first!';
wp_send_json( $result );
You can also send a JSON with the success
property set to false
for you like this:
$result = 'You have not uploaded project file, please upload first!';
wp_send_json_error( $result, 400 );
That will result in something like:
{
"success": false,
"data": "You have not uploaded project file, please upload first!"
}