Ajax : Why success displays 0?

前端 未结 10 1139
生来不讨喜
生来不讨喜 2021-01-01 19:02

I use ajax with jquery and when I tried to display the result in popup. Then alert always displays 0

success : function(results) { 
alert(result         


        
相关标签:
10条回答
  • 2021-01-01 19:19

    May be you are trying without login. so you need to use this action.

    add_action('wp_ajax_nopriv_my_action', 'my_action_callback');

    you will get response. :)

    0 讨论(0)
  • 2021-01-01 19:23

    Found it.

    It need to add die(); before the end of my own ajax function in function.php.

    Because there is one line of script in admin-ajax.php after my own ajax_action that says: die('0'); So we need to die() script before die('0').

    0 讨论(0)
  • 2021-01-01 19:29

    Those who get error 0 :), action => 'action'

    var data = {'action': 'my_action', 'data': form_data };
    
    $.post(ajaxurl, data, function(response) { alert(response);});
    
    0 讨论(0)
  • 2021-01-01 19:30

    I was adding the "action" incorrectly. You have to prefix your action with wp_ajax_gd_.

    add_action('wp_ajax_gd_[ACTION NAME]', '[CALLBACK FUNCTION NAME]')
    

    and in the JS jQuery post:

    var data = {
        'action': '[ACTION NAME]',
    };
    

    I found Wordpress' documentation very unclear about this part.

    0 讨论(0)
  • 2021-01-01 19:31

    In your PHP function, make sure you're using echo instead of return.

    This was happening for me in a WordPress theme.

    function doAjax() {
        $result = getPosts();
        echo json_encode($result, true);
        die();
    }
    
    0 讨论(0)
  • 2021-01-01 19:40

    Try to add die(); or exit(); at the very last line of the function.

    0 讨论(0)
提交回复
热议问题