How to call a PHP function from Javascript in WordPress

Here’s an example:

Use this sample JavaScript code:

jQuery(document).on('click', '.some-element', function(e){
    var ipc = jQuery(this).data('collection-id');
    jQuery('.some-other-element').show();

    jQuery.ajax({
        method: 'post',
        url: ipAjaxVar.ajaxurl,
        data: {
            collection_id: ipc,
            action: 'my_function',
        }
    }).done(function(msg) {
        // Do something when done
    });

    e.preventDefault();
});

PHP (include the function in your plugin, do not use a separate file):

// Include the JavaScript above in your plugin
wp_enqueue_script('main', plugins_url('js/jquery.main.js', __FILE__), array('jquery'), '', true);

wp_localize_script('main', 'ipAjaxVar', array(
    'ajaxurl' => admin_url('admin-ajax.php')
));

add_action('wp_ajax_my_function', 'my_function');

UPDATE:

Add the PHP code to your main plugin file. Create a JavaScript file – js/jquery.main.js – and add the code above. That should do the trick.

Leave a Comment