When doing AJAX call in WordPress, you should always post to admin-ajax.php
file. Here’s how you do that.
In your plugin or functions.php
:
function process_my_ajax_call() {
// Do your processing here (save to database etc.)
// All WP API functions are available for you here
}
// This will allow not logged in users to use the functionality
add_action( 'wp_admin_my_action_no_priv', 'process_my_ajax_call' );
// This will allow only logged in users to use the functionality
add_action( 'wp_admin_my_action', 'process_my_ajax_call' );
You’ll also have to pass the correct URL to the admin-ajax.php
file to your JavaScript and wp_localize_script
function is great just for that:
function localize_my_scripts() {
$localizations = array(
'ajaxUrl' => admin_url( 'admin-ajax.php' ),
);
wp_localize_script( 'my-script-handle', 'myVars', $localizations );
}
add_action( 'wp_enqueue_scripts', 'localize_my_scripts' );
Now in your JavaScript:
$.ajax({
url: myVars.ajaxUrl, // Notice the AJAX URL here!
type: 'post',
data: 'username=test&action=my_action', // Notice the action name here! This is the basis on which WP calls your process_my_ajax_call() function.
cache: false,
success: function ( response ) {
// Parse ajax response here
// Do something with the response
},
error: function ( response ) {
// Handle error response here
};
});
This is, of course, just a huge summary of how to make AJAX calls in WordPress. You will still need to verify nonces, create a proper AJAX response using WP_Ajax_Response class and then enqueue the wp-ajax-response script on frontend to process WP’s response. If you want to learn more, there’s a comprehensive guide to AJAX in WordPress written by Ronald Huereca and it’s available for free!