最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Ajax Multi Response Problem

programmeradmin5浏览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.

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
Add a comment  | 

1 Answer 1

Reset to default 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!"
}

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论