How to send AJAX request in Wordpress
What is AJAX request
An AJAX request is a simple GET or POST to an URL. You pass some custom parameters and this URL answers you with some data. You can read this data using JavaScript and you can perform further actions according to data.
AJAX request is used to transfer the data between client and server without reloading or refreshing the entire page.
AJAX request in WordPress
Now a days, alomost all frameworks and CMSs are using its own method to route a HTTP/HTTPS request. WordPress also use the same concept. In WordPress, we send all AJAX request to a common URL, then wordpress internally calls the corresponding method according to the parameters which we have sent with the request.
The common URL to send the request is http://domain.com/wp-admin/admin-ajax.php
You can use the admin_url( ‘admin-ajax.php’ ) function of WordPress to get this url.
We write the script on both side (Client and Server) to send and handle an AJAX request.
Client Action
We use JavaScript/jQuery to write the client action script. Here is the simple code which you can use to send the AJAX request with parameters:
jQuery(document).ready({
var data = {
'action': 'my_ajax_request',
'post_type': 'POST',
'name': 'My First AJAX Request'
};
jQuery.post("", data, function(response) {
console.log( response );
}, 'json');
});
Server Action
After sending the AJAX request via JavaScript/jQuery, we have to process this request on server to send the response to the client. We use WordPress Actions to handle this AJAX request. WordPress will read the value of action parameter to call the corresponding method on server. In the above case we have used “my_ajax_request”.
Now you have to add the below function in the functions.php file of WordPress theme.
add_action( 'wp_ajax_my_ajax_request', 'tft_handle_ajax_request' );
add_action( 'wp_ajax_nopriv_my_ajax_request', 'tft_handle_ajax_request' );
function tft_handle_ajax_request() {
$name = isset($_POST['name'])?trim($_POST['name']):"";
$response = array();
$response['message'] = "Successfull Request";
echo json_encode($response);
exit;
}
We can use this repsonse the JavaScript handler to process the response.