I am writing a plugin for the first time, and I have a problem.
I am using AJAX in my plugin. My JavaScript file is in the folder ../wp-content/plugins/myplugin/js/
, and in it I am trying to call a PHP file, which is in the folder ../wp-content/plugins/myplugin/
jQuery.ajax({
url: "/wp-content/plugins/myplugin/myfile.php?myparam=" + myparam,
context: document.body
});
My question is: How can I get this URL reference work independent of, where the user installed the plugin.
Because when for example a user install this plugin in http://localhost/subdir/
, the reference is not correct.
Can I somehow create a relative link ?
3 Answers
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,
...
})