• I have main class A(ex: dashboard), and 2 class B (ex: state),C (ex: city)… and create a callback action in class B/C.

    In class A I call hooks function from class B,C
    Ex: declare class and call hooks

    class_state = new State();
    class_state->hooks()
    
    // function hooks from class B/C
    function hooks(){
    add_action('wp_ajax_state_change', array($this,'state_change'));
    }

    When I send ajax I got message Bad request, the javascript is success enqueu, if I put above function in function.php it ok

    Tks

    • This topic was modified 6 years, 11 months ago by whatwhenwhere.
Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    The action value that’s used to construct the action tag must be passed as a value in the POSTed data array. You’ve not provided the jQuery call, so we cannot say if that is done properly. Additionally, assuming that the action value is properly passed, the user must be logged in for your hook to fire. To work with non-logged in users, you must also hook ‘wp_ajax_nopriv_state_change’. Also realize that if two classes both hook the same action, both handlers will be called in an undefined order. That may or may not be your intention.

    For more on properly passing action values, see the Ajax chapter of the Plugin Handbook.

    Thread Starter whatwhenwhere

    (@whatwhenwhere)

    below my Jquery script, tks @bcworkz

    `jQuery(‘#quoc_gia’).on(‘select2:select’, function (e) {
    jQuery.ajax({
    type: ‘POST’,
    url:ajaxurl,
    dataType: ‘json’,
    data:{‘quocgia’:’test’,action: ‘quocgia_change’},
    success:function(res) {

    },
    error: function(MLHttpRequest, textStatus, errorThrown){
    alert(errorThrown);
    }
    });
    });

    Moderator bcworkz

    (@bcworkz)

    Try this in your hooks() callback:

    add_action('wp_ajax_quocgia_change', array($this,'state_change'));
    add_action('wp_ajax_nopriv_quocgia_change', array($this,'state_change'));

    I’m assuming the $class_state->state_change() Ajax handler is appropriate for both logged in and non-logged in users. The action tag that’s hooked must relate to the ‘action’ data item in your jQuery .ajax() call. In the code you posted in your OP, the class_state object variable is missing the $ PHP variable symbol. I imagine that is a mere oversight in putting together a quick example and your actual code does not contain any such syntax errors. It’s also missing a terminal ; ??

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘wp_ajax_{action_name} not working in multi class’ is closed to new replies.