0

I am trying to perform ajax request in my plugin. What I have done is:

    Class Someclass {

        public function __construct(){

        }

        public function current_page_function(){

            add_action(
                "wp_ajax_test_ajax",array($this,'test_ajax')
            );

            $this->data=array();

            View_Includer::load('index',$this->data,false,false,false,false,true,false,false);
        }

         public function test_ajax(){
            wp_send_json_success('Science achieved!');
            exit();
        }

}

Script:

    var send_ajax_request = function( cpt_id ) {

        // Define the function and the data to send to the server.
        var data = {
            'action':    'test_ajax',
            'post_type': cpt_id
        };

        // Send the request to the server and handle the response.
        jQuery.post( Essestials.ajaxurl, data, function( response ) {
            return response;
            // Handle your response here.
        });

    };

When I do this, the wordpress return 400 error code. But when I do as below:

    Class Someclass {

        public function __construct(){
            add_action(
                "wp_ajax_test_ajax",array($this,'test_ajax')
            );
        }

        public function current_page_function(){
            $this->data=array();
            View_Includer::load('index',$this->data,false,false,false,false,true,false,false);
        }

         public function test_ajax(){
            wp_send_json_success('Science achieved!');
            exit();
        }
    }

it returns the following response :

    {success: true, data: "Science achieved!"}

what wrong am I doing on the first process ? Why it works only when I add the hook in constructor ? Any kind of helps are highly appreciated. Thanks.

1 Answer 1

0

Some actions must be registered as early as possible. When you put it in the "current_page_function" method, (depending on your program) it might be too late.

Hence, the wp_ajax_* hook cannot find your action, and it returns the error.

2
  • is it simply the reason ? I mean ajax request is proceeded only when action is registered and page is fully loaded. By that time , wp_ajax_* should have find the hook. Can you please make it more clear ? Thanks.
    – TShrestha
    Commented Feb 4, 2019 at 7:34
  • Without knowing the full code I cannot confirm it 100%. Yes, your ajax request is called when the page is loaded. But, every time you call ajax function, WordPress doing it's program-cycle again (bootstrapping, registering hooks, init, instantiating classes, etc) to return a response. Because that's how web works.
    – hamdirizal
    Commented Feb 4, 2019 at 23:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.