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 ?
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 ?
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,
...
})
I'm a beginner, but this worked for me
Add the following in functions.php. Note that 'wp_ajax' is a prefix by convention and 'do_something' is my arbitrarily chosen action name:
add_action( 'wp_ajax_do_something', 'do_something' );
function do_something() {
//really, go ahead, do something
die("return something");
}
To make the ajax call from the browser (client side), I was able to find my endpoint using wp.ajax.settings.url
. wp
global var is defined on the window object.
//do_something here must match above, you can add other params to this obj
var data = { action: 'do_something' };
jQuery.post(wp.ajax.settings.url, data, function(response) {
console.log('Result: ' + response);
});
I have WordPress 4.6.1 (latest on time of writing) and some plugins installed. I referred to this reference that incorrectly says that ajaxurl is defined, but it's not in my case: https://codex.wordpress/AJAX_in_Plugins
I faced the same issue.
I wanted to use my own endpoint instead the admin-ajax endpoint because I have rewrite rules populating all the variables I need to run the ajax actions.
Thus, using (as said in the codex)
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': ajax_object.we_value // We pass php values differently!
};
jQuery.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});
and
add_action( 'wp_ajax_my_action', 'my_action' );
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
just makes my code more complicated.
I ended up doing this and it seems to work:
jQuery.ajax({
type: "post",
url: MYCUSTOMENDPOINT?ajax_action,
dataType: 'json',
...
combined with:
add_action( 'init', 'rewrite_rules');
add_filter( 'template_include','handle_ajax_action');
function rewrite_rules(){
add_rewrite_tag(
'%ajax_action%',
'([^&]+)'
);
}
function handle_ajax_action($template){
$success = null;
// since the "ajax" query variable does not require a value, we need to check for its existence
if ( !$action = get_query_var( 'ajax_action' ) ) return $template; //ajax action does not exists
$result = array(
'input' => $_REQUEST,
'message'=> null,
'success'=> null,
);
$success = ...
if ( is_wp_error($success) ){
$result['success'] = false;
$result['message'] = $success->get_error_message();
}else{
$result['success'] = $success;
}
header('Content-type: application/json');
send_nosniff_header();
header('Cache-Control: no-cache');
header('Pragma: no-cache');
wp_send_json( $result );
}