0

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.

2
  • Normally, shortcodes don't echo they return. I imagine we would need to see more code here.
    – Howdy_McGee
    Apr 14 '20 at 3:36
  • Give full code details
    – Maidul
    Apr 14 '20 at 4:42
3

As 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!"
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.