In my plugin, I have some jQuery-Ajax code that processes form data and adds it to the database as soon as the button is clicked. Since many people have a different path to
In WordPress, all AJAX requests must be made to the following URL:
http://www.example.com/wp-admin/admin-ajax.php
You should not make an AJAX request directly to a file residing in the plugin or theme directory.
Also, do not hard-code the above URL, instead you should use the following function to construct the URL:
Alternatively to the above, you can use wp_localize_script(), but this is not required, the above is fine too.
Note: Don't worry about the "admin" part, this URL is the correct one to use for all users, including non-logged-in (guest) users.
You need to let WordPress know which function should process your AJAX request.
For that purpose you'll create a custom function, and register it using the wp_ajax_*
and wp_ajax_nopriv_*
hooks:
add_action('wp_ajax_mycustomfunc', 'mycustomfunc'); // Logged-in users
add_action('wp_ajax_nopriv_mycustomfunc', 'mycustomfunc'); // Guest users
function mycustomfunc() {
$whatever = esc_html($_POST['whatever']);
echo 'It works: '.$whatever;
exit; // This is required to end AJAX requests properly.
}
Finally, here is how you would make a proper AJAX request:
(function ($) {
$(document).ready(function () {
var my_data = {
action: 'mycustomfunc', // This is required so WordPress knows which func to use
whatever: "yes it is" // Post any variables you want here
};
jQuery.post(ajax_url, my_data, function(response) {
alert('Got this from the server: ' + response);
});
});
})(jQuery);
If you had to put it all into one file, here's how you'd do it:
// Register my custom function for AJAX processing
add_action('wp_ajax_mycustomfunc', 'mycustomfunc'); // Logged-in users
add_action('wp_ajax_nopriv_mycustomfunc', 'mycustomfunc'); // Guest users
function mycustomfunc() {
$whatever = esc_html($_POST['whatever']);
echo 'It works: '.$whatever;
exit; // This is required to end AJAX requests properly.
}
// Inline JavaScript
add_action('wp_footer', 'my_inline_js');
function my_inline_js() { ?>
Note: For the ajax_url
part, you could use wp_localize_script() instead of setting it manually, but it is less flexible as it requires to specify an existing enqueued script, which you might not have.
Note: Also, for outputting inline JavaScript manually into a page, the wp_footer
hook is the correct one to use. If using wp_localize_script() then you would use the wp_enqueue_scripts hook instead.