Site icon Hip-Hop Website Design and Development

Ajax call returns 0 when add_action is inside a class in functions.php

Ajax call returns 0 as output. I am sure that hook is not working and it’s not calling the test2 method. Why is add_action(... not working inside class in functions.php?

——–Wrap inside functions.php Starts——-

class test{
    public function __construct() {
        add_action( 'wp_ajax_test2', array( $this, 'test2' ) );
    }                       
    public function test1() { ?>
        <script>
            jQuery(document).ready(function($){
                var ajaxurl = "<?php echo get_site_url();?>/wp-admin/admin-ajax.php";
                var data = {'action':'test2'};
                 $.ajax({   
                    url: ajaxurl,
                    type: "POST",
                    data: data,
                    success: function(val) {
                        alert(val);
                    },
                }); 
            });             
        </script><?php 
    }               
    public function test2(){
        echo "success";
        exit;
    }       
}

——–Wrap inside functions.php Ends——-

Created an object in a template page and call to test1 method:

$ob_call = new test;
$ob_call->test1();