0

I am expecting the following code to alert 'test', instead it alerts 'testtest0'. Why?

The code runs some javascript in the admin footer, it's response is just echoed via the functions test() and get_test();

<?php

class Test_Class {

    public function __construct() {
        add_action( 'admin_footer', array( $this, 'test_js' ) );
        add_action( 'wp_ajax_test', array( $this, 'test' ) );
    }

    public function test_js() { 
        global $post; ?>
        <script>
            jQuery(document).ready(function($) {

                function runTest() {

                    var data = {
                        'action': 'test',
                    };

                    jQuery.post(ajaxurl, data, function(response) {
                        alert( response );
                    });

                }

                runTest();

            });
        </script>
    <?php }

    public function test() {

        $test = $this->get_test();
        echo $test;

    }

    public function get_test() {

        $string = 'test';
        return $string;

    }

}

$new = new Test_Class();
1

Ajax callbacks should always finish with a die(), otherwise it will output that 0 you are seeing. I'm not sure why it's outputting another "test"

1
  • Yes that fixes the end 0, but why the loop of testtest? – Steveo May 3 '17 at 15:26

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.