How do I use Ajax in a Wordpress plugin?

后端 未结 1 1849
暗喜
暗喜 2020-12-22 07:48

I have a Wordpress site with 2 dropdown boxes. When I select an option in the first dropdown box I want the 2nd one to be refreshed with data from a PHP function. For that I

相关标签:
1条回答
  • 2020-12-22 08:09

    Use the native methods that Wordpress provides to you to leverage ajax requests.

    In your plugin file, we need to add a couple actions so that we can send ajax requests through and have them parsed by the admin-ajax.php file.

    add_action('wp_ajax_nopriv_ajax_request', 'ajax_controller');
    add_action('wp_ajax_ajax_request', 'ajax_controller');
    

    Now we build out an ajax controller in our plugin file. The purpose of this is to act as a controller that will switch it's output based on the FN parameter supplied by the ajax request (more on this later)

    function ajax_controller(){
        $ret = ''; //our return variable
        switch($_REQUEST['fn']):
            case 'status' :
                $ret = update_status($_REQUEST['status']);
                break;
        endswitch;
        echo $ret;
        die(); //this makes sure you don't get a "1" or "0" appended to the end of your request.
    }
    

    Please note that the update_status() function was created to encapsulate your above php code.

    Now we have the actions bound, and a controller that we can use endlessly to retrieve data. We just need to make a couple modifications to the ajax call. First, we can use ternary assignment for the 'rent/sale' switch, as opposed to 2 ajax calls, which will clean things up. Second, we need to change the url address to the /wp-admin/admin-ajax.php file.

    var $status = (this.value == "sale") ? this.value : 'rent';
    jQuery.ajax({
        type: "POST",
        url: "/wp-admin/admin-ajax.php",
        data: { 
           action: 'ajax_request', 
           fn : 'status', //this is the $_REQUEST['fn'] from above
           status : $status },
        success: function(data){
            alert('Sale' + data['min']['data'][0]);
        }
    });
    

    The action parameter is required, the fn is a result of my coding principles. The action attribute must directly match what comes after add_action('wp_ajax_nopriv_ and add_action('wp_ajax_.

    This should resolve it.

    0 讨论(0)
提交回复
热议问题