Wordpress: how to call a plugin function with an ajax call?

后端 未结 3 1669
一生所求
一生所求 2020-12-08 03:26

I\'m writing a Wordpress MU plugin, it includes a link with each post and I want to use ajax to call one of the plugin functions when the user clicks on this link, and then

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-08 04:04

    Just to add an information. If you want to receive an object from a php class method function :

    js file

    jQuery(document).ready(function(){
    jQuery(".foobar").bind("click", function() {
        var data = {
            'action': 'getAllOptionsByAjax',
            'arg1': 'val1',
            'arg2': $(this).val() 
        };
        jQuery.post( ajaxurl, data, function(response) {
           var jsonObj = JSON.parse( response );
        });
    });
    

    php file

    public static function getAllOptionsByAjax(){
    
        global $wpdb;
    
        // Start query string
        $query_string  =  "SELECT * FROM wp_your_table WHERE col1='" . $_POST['arg1'] . "' AND col2 = '" . $_POST['arg2'] . "' ";
    
        // Return results
        $a_options = $wpdb->get_results( $query_string, ARRAY_A );
        $f_options = array();
        $f_options[null] =  __( 'Please select an item', 'my_domain' );
        foreach ($a_options as $option){
            $f_options [$option['id']] = $option['name'];
        }
        $json = json_encode( $f_options );
        echo $json;
        wp_die();
    }
    

提交回复
热议问题