Custom PHP endpoint for a plugin’s AJAX call

First of all, you shouldn’t call your own PHP file. You should use admin-ajax endpoint. Documentation

On admin side, you could use ajaxurl to get URL for AJAX calls. On front side you have to declare by yourself variable with url. This is written in documentation:

Note: Unlike on the admin side, the ajaxurl javascript global does not get automatically defined for you, unless you have BuddyPress or another Ajax-reliant plugin installed. So instead of relying on a global javascript variable, declare a javascript namespace object with its own property, ajaxurl. You might also use wp_localize_script() to make the URL available to your script, and generate it using this expression: admin_url( ‘admin-ajax.php’ )

This should resolve problem:

add_action( 'wp_head', 'front_ajaxurl' );
function front_ajaxurl() {
    wp_register_script( 'admin_ajax_front', plugin_dir_url(__FILE__) . 'script.js' );
    $translation_array = array(
        'ajaxurl' => admin_url( 'admin-ajax.php' )
    );
    wp_localize_script( 'admin_ajax_front', 'front', $translation_array );
    wp_enqueue_script( 'admin_ajax_font', false, array(), false, true ); // last param set to true will enqueue script on footer
}

And then in your JS file:

$.ajax({
    url: front.ajaxurl,
    ...
})

Leave a Comment