How To Use Ajax In WordPress

Over the last decade, AJAX (Asynchronous JavaScript and XML) has become a vital part of web based application. AJAX helps us update the webpage content (or a part of it) without reloading the page. The basic mechanism AJAX follows is whenever any event (button click, mouse drag, mouse over, keyboard actions etc.) occurs, a call is generated to a JavaScript program which calls another program on the web server. The program processes the request and returns the response to the JavaScript program asynchronously which ultimately updates the web page (or any other action that is required) on the go.

AJAX in WordPress:

AJAX is basically an independent framework and it can be used in WordPress too. You can use it the way you want, but AJAX is already used in WordPress administration panel, so it is already implemented and we just have to use the functions that are available.

AJAX Usage in WordPress:

You can use AJAX in an entirely effective way with the following roles in WordPress:

WordPress AJAX Hooks:

All the requests either on front-end site or back-end administration panel should be submitted to admin-ajax.php which is located in wp-admin folder. There is a required parameter by admin-ajax named “action”, which will help fire on of the below mentioned WordPress hooks based on whether the user is logged in or not:

Heremy-action and the “function_name” should be replaced with the action and function name required (as we normally do for any other WordPress hook).

The JavaScript Code:

We can use any of the multiple methods that we normally use to make an asynchronous request to server using jQuery like $.ajax, $.post or $.get. We would be using $.ajax method in this article to show the process of making request to admin-ajax.php:

Implementing the AJAX Request:

The function we used in the hook will implement the functionality and return the response. The code will now become:

Get WordPress admin-ajax.php URL:

Mostly we use AJAX in our plugins and themes, which are more likely to change the URL’s and paths depending upon the server. The best approach to get admin-ajax.php’s URL is to use WP_LOCALIZE_SCRIPT which will allow us to get the URL dynamically:

The above will create a JavaScript object on runtime and on the dynamic admin-ajax.php URL which we can use in our AJAX call. The JavaScript code now will be updated like this:

User Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

    Get in Touch