Now a days a lot of wordpress themes are build with AJAX functionality. All these themes can retrieve and add posts, pages, comments, users etc using AJAX. Integrating AJAX into WordPress is very handy if you want to create a single page wordpress theme. In this article I will explain the core about integrating AJAX into WordPress.
wp-admin/admin-ajax.php
This file is the core of AJAX in WordPress. All the AJAX requests are made to this file and this file returns the appropriate result. You can either make a GET or POST request to this URL but its compulsory to provide the API name. API name identifies which function you want this URL to execute.
This file doesn’t provide any output by default therefore you need to explicitly produce output(HTTP response content) using explicitly defined actions.
Defining AJAX Functions
Suppose you want to check if user is logged in or not using AJAX then you can use a function named logged_in_check(you can name it anything) and register it via wp_ajax_ and wp_ajax_nopriv_ wordpress actions.
{
//check if it is a AJAX request
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
//check if user is logged in or nor
if(is_user_logged_in())
{
echo "TRUE";
}
else
{
echo "FALSE";
}
die();
}
//seems like a anchor link or form request
else
{
//handle non AJAX request
//do the same operation.
//redirect back to the referer page.
header("Location: ".$_SERVER["HTTP_REFERER"]);
die();
}
}
//here api name is logged_in_check
//this action is executed if user is logged in
add_action("wp_ajax_logged_in_check", "logged_in_check");
//this action is executed if user is not logged in
add_action("wp_ajax_nopriv_logged_in_check", "logged_in_check");
Put this code via theme or plugin.
Now you can make request to the URL this way: http://myDomain.com/wp-admin/admin-ajax.php?action=logged_in_check
If you want to make a POST request then make sure you have input element name as “action” and value as “logged_in_check”.
<input type="text" name="action" value="logged_in_check" />
</form>
Users might have AJAX disabled in that case you can make a non-AJAX request to the same URL and in the else condition of the example shown you can handle the logic and then redirect user back to the referer URL.
Example AJAX code looks like this
xhr.open("GET", "http://themes.qnimate.com/qplog/wp-admin/admin-ajax.php?action=logged_in_check");
xhr.setRequestHeader("X_REQUESTED_WITH","xmlhttprequest");
xhr.onload = function(){
console.log(xhr.responseText);
}
xhr.send();