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();

Read more here: AJAX call returns ‘testtest0’ instead of ‘test’ – why?


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: