Using AJAX in WordPress

Home » Programming » Using AJAX in WordPress

Using AJAX in WordPress

What is AJAX?

AJAX is a combination of HTML, CSS and JavaScript/jQuery code that enables to send data to a script, next to receive it and process the response without reloading the page.

How AJAX works in WordPress?

WordPress Ajax acts as a special Ajax dedicated WordPress action and is capable of handling the server side aspect of it. Every AJAX request goes through the admin-ajax.php file in the wp-admin folder. Each request needs to supply GET or POST method called action. Based on this action, the code in admin-ajax.php creates two hooks, wp_ajax_<ACTION_NAME> and wp_ajax_nopriv_<ACTION_NAME>,  where <ACTION_NAME> is the value of the GET or POST variable action.

Let’s implement a simple ajax example in WordPress to understand it properly.

1. Create a page and ad  the below code in it

HTML form

We will be using nonce for security reasons

The word “nonce” is an abbreviation for the term “number used once” and is a string generated by WordPress. It acts as a special token whenever user doing a specific operation such as submission of a form, deletion of a post etc. It is like a temporary secret key or fingerprint which is unique only to you. And it can only ever be used by you for a specific operation and it is extremely difficult to be guessed by somebody else. The nonce value is valid for 24 hours after which it expires and a new one will be generated. This ensures that someone cannot copy an old nonce and re-inject it into the URL of an operation or request.

 

2. Add the below code in the functions.php file of the current active theme

add_action( ‘wp_ajax_nopriv_<ACTION_NAME>’, <FUNCTION_NAME> );
add_action( ‘wp_ajax_nopriv_<ACTION_NAME>’, <FUNCTION_NAME> );

The detailform is the <ACTION_NAME>action parameter which will be passed in the data array in the below jquery code.
The second parameter detailform is the callback<FUNCTION_NAME> function which is to be executed.

wp_ajax_nopriv_ – This is required when logged in is not necessary on website.
wp_ajax_- This is required when logged in is compulsory on website.

You must add both the ways to make sure the data gets processed.

 

3. The ajaxurl which is the default url for WordPress. Add this in the functions.php file of the current active theme.

 

4. Create new app.js file in the active theme directory and paste the below code.

 

Conclusion

A quick recap, the four steps involved are:

  1. Make the AJAX call.
  2. Create the function, which will handle the action.
  3. Add the function to the hook.
  4. Create success handlers as needed.
I’m a positive and enthusiastic web and mobile developer – and I relish a challenge.