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
<form role="form" id="contact_me">
<?php wp_nonce_field( 'my_form' ); ?>
<div class="form-group">
<label for="form_cb">What is capital of India?</label>
<input type="text" class="form-control" name="name" id="form_cb">
</div>
<button type="submit" class="btn btn-default" id="submit_btn">Submit</button>
</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
function detailform() {
$error = '';
$status = 'error';
if (empty($_REQUEST['name'])) {
$error = 'Field cannot be empty';
} else {
$nonce = $_REQUEST['_wpnonce'];
if (!wp_verify_nonce($nonce, 'my_form')) {
$error = 'Verification error, try again.';
} else {
if ( $_REQUEST['name'] == 'Delhi'){
$status = 'success';
$error = $sendmsg;
} else {
$error = 'Some errors occurred.';
}
}
}
$resp = array('status' => $status, 'errmessage' => $error);
echo json_encode($resp);
die();
}
add_action( 'wp_ajax_detailform', 'detailform' );
add_action( 'wp_ajax_nopriv_detailform', 'detailform' );
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.
add_action('wp_head','pluginname_ajaxurl');
function pluginname_ajaxurl() {
?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
4. Create new app.js file in the active theme directory and paste the below code.
$('#submit_btn').click(function (e) {
e.preventDefault();
var error = false;
var name = $('#form_cb').val();
var nonce = $('#_wpnonce').val();
if (name.length == 0) {
var error = true;
$('#form_cb').css("border-color", "#D8000C");
}
if (error == false) {
$.ajax({
url: ajaxurl,
data: {
'action':'detailform',
'name': name,
'_wpnonce': nonce
},
success:function(response) {
if (response.status == 'success') {
alert("You are right");
}else{
alert("You are wrong");
}
},
error: function(errorThrown){
console.log(errorThrown);
}
});
}
});
Conclusion
A quick recap, the four steps involved are:
- Make the AJAX call.
- Create the function, which will handle the action.
- Add the function to the hook.
- Create success handlers as needed.