Friday, February 22, 2019

Proper way to use WordPress function with AJAX PHP file

In general, trying to access directly any php file in your theme (or plugin) is going to fail for various reasons.
Using admin-ajax.php is the way to go here. To use it, you would do something like the following:

<?php
$action_name = 'plugin_my_personal_taxonomy';
add_action ('wp_ajax_' . $action_name, array(self::class, 'ajax_call_your_function'));
add_action ('wp_ajax_nopriv_' . $action_name, array(self::class, 'ajax_call_your_function'));

public static function ajax_call_your_function() {
    wp_send_json_success("Hello");
}
And from jQuery:
jQuery(document).ready(function(){
    var $ = jQuery, body = $(document.body);

    $.ajax ({
        url: MY_TAXONOMY_PLUGIN_CORE.ADMIN_URL + '/admin-ajax.php',
        type: 'POST',
        dataType: 'JSON',
        data: {
            action: 'plugin_my_personal_taxonomy'
        },
        success: function (resp) {
            console.log(resp);
        },
        error: function (xhr, ajaxOptions, thrownError) {
            // this error case means that the ajax call, itself, failed, e.g., a syntax error
            // in your_function()
            alert ('Request failed: ' + thrownError.message) ;
        },
    });
});

No comments:

Post a Comment