Wordpress AJAX doesn't work - response 0

后端 未结 3 1893
隐瞒了意图╮
隐瞒了意图╮ 2021-01-21 11:37

I want add AJAX support to my plugin and I have huge problem with this simple thing. WordPress isn\'t permitting me to use normal AJAX and I need to use WordPress version.

相关标签:
3条回答
  • 2021-01-21 12:16

    remove

    <script>alert('echo');</script>
    

    your response should be echo if you check your console. I suspect all the above code is in your plugin functions file. Basically the php function should be placed in the functions file.

    The jquery should be placed in the template from which you want to receive the response.

    Place this in your functions file...remove the jquery from the class...

    add_action('wp_print_footer_scripts', 'print_js', 1000);
    
        function print_js() { ?>
        <script type="text/javascript">
        jQuery(document).ready(function(){
    
            jQuery.ajax({
                url: 'wp-admin/admin-ajax.php',
                type: 'POST',
                data: {
                    'action': 'test_callback',
                    'whatever': 'text'
                },
                success: function (output) {
                  alert(output);
                }       
            }); 
    
        });
        </script>
    <?php
    }
    

    Move this outside your class...

     function test_callback() {
                        $whatever = 8;
                        echo $whatever;
                        die();
     }
    
     add_action( 'wp_ajax_nopriv_testaction', 'test_callback' );
     add_action( 'wp_ajax_testaction', 'test_callback' );
    
    0 讨论(0)
  • 2021-01-21 12:26

    Just make sure that you have put the function 'fq_tag_support_callback()' in your plugin's main file.

    0 讨论(0)
  • 2021-01-21 12:26

    I see few problems here. Action should inside the data object, not as a jQuery Ajax parameter. Also in the callback function data is stored in $_POST variable.

    function test_callback() {
    
        $whatever = $_POST['whatever'];
        echo $whatever;
    
        die();
    }
    add_action('wp_ajax_nopriv_fqtag', 'test_callback');
    add_action('wp_ajax_fqtag', 'test_callback');
    
    function print_js() {
        ?>
        <script type="text/javascript">
            jQuery.ajax({
                url: <?php echo admin_url('admin-ajax.php'); ?>,
                type: 'POST',
                data: {
                    action: 'fqtag',
                    whatever: 'text'
                },
                success: function (output) {
                    alert(output);
               }       
            });
        </script>
        <?php
    }
    add_action('wp_print_footer_scripts', 'print_js', 1000);
    ?>
    
    0 讨论(0)
提交回复
热议问题