Well, yes – there is a lot better way of doing this.
First of all, you should never do any direct requests to files inside wp-content
directory. Securing and hardening WordPress properly is much harder, if some plugin does such requests.
And of course there is no need of doing them.
WP has built-in mechanism for AJAX requests. You can read full docs here: https://codex.wordpress.org/AJAX_in_Plugins
All your AJAX requests should be sent to wp-admin/admin-ajax.php
. This way you can process them efficiently using these hooks:
wp_ajax_my_action
wp_ajax_nopriv_my_action
So somewhere in your plugin PHP file you do:
// Enqueue your JS file
function my_enqueue($hook) {
wp_enqueue_script( 'ajax-script', plugins_url( '/js/my-script.js', __FILE__ ), array('jquery') );
// in JavaScript, object properties are accessed as ajax_object.ajax_url
wp_localize_script( 'ajax-script', 'My_Ajax_bject',
array( 'ajax_url' => admin_url( 'admin-ajax.php' )
);
}
add_action( 'admin_enqueue_scripts', 'my_enqueue' );
// AJAX request handler
function my_action() {
global $wpdb; // you can use global WP variables and so on
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
wp_die();
}
add_action( 'wp_ajax_my_action', 'my_action' );
And in your JS file:
jQuery(document).ready(function($) {
var data = {
'action': 'my_action',
'whatever': 1
};
$.post(ajax_object.ajax_url, data, function(response) {
alert('Got this from the server: ' + response);
});
});