What is AJAX?
Ajax has been in web development as a way of communicating between the front end and the back end of web applications for quite some time. With Ajax, the frontend pages do not need to reload after it makes requests to the backend. Chances are quite high, even as a new developer, you must have included Ajax calls in your web applications.
If you are a WordPress developer or new to Wordpress custom website development, you might be looking for ways to do Ajax requests. You probably implemented it the way you used to do it in other web applications that do not utilize the power of wordpress. And pretty sure, you must have got an error. Then, you got frustrated and got frustrated; you google 'how tos' one after another. And, now you hit this post.
Welcome, I am here to help you. let me show you how to do it in WordPress style!
AJAX in WordPress
Making Ajax requests in WordPress is different from how you do it in other web applications. Remember WordPress is a Web Application. It already utilizes Ajax as a technology. All the Ajax requests in WordPress are first directed to one file called admin-ajax.php.
Now lets us see how to implement it. We are going to create a page based on a custom wordpress template and make Ajax calls from that page.
These are the steps that we are going to do
Create a custom page template
Add a custom script file
Add code required to run the external scripts and AJAX call in the functions.php file.
please note that you need to be familiar with WordPress and WordPress child themes in order to benefit from this post.
Creating the page based on a custom page template
This part is not strictly related to making Ajax requests. However, I choose a custom template because there is a good chance that you would make an Ajax request in a custom code that you adding as a WordPress developer.
STEP 1
In your child-theme folder, add a file named contact-form.php
, and add the following code.
<?php
/**
* Template Name: contact-form-template
**/
?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php wp_head(); ?>
</head>
<section style="margin: 15px 0 0 10vw">
<div><?php get_template_part( 'template-parts/content', get_post_type() ); ?> </div>
<form method='post' id='contact-form'>
<label>Name:</label> <input id="myInput" type='text' />
<input type='submit' />
</form>
<div><br />Your name is <span id="displayName"><span></div>
</section>
<?php wp_footer(); ?>
</body>
</html>
The above code creates the interface that we need to demonstrate the AJAX call. All you need here is actually simple HTML form.
I used get_template_part( 'template-parts/content', get_post_type() )
to get the content of the contact page that we are going to create in a few seconds. template-parts/content is a theme template that exists in many WordPress themes. It has code to read the content of a page you add to WordPress sites. You do not need to know get_template_part
() to understand how to make AJAX calls in WordPress. It is not required.
wp_head() is a WordPress function that executes scripts in the head tag on the front end. As we use Jquery to make AJAX calls, you need this function on the custom template.
STEP 2
Now go to the WordPress Dashboard and create a new page and make the following changes
Note: you can enter anything you need here. It is not important to understand how Ajax works. The most important thing here is to change the Template that this page is built on. When you click on Template drop-down box, you should be able to see contact-form-template
. Select it and click on publish button.
you should see a simple form below at http://localhost/tecforfun/contact-me/
Adding a custom script file
Now in your child theme's root folder, create another folder named scripts, and add a new file name contact.js inside this folder. Add the following code to this file
(function($) {
jQuery("#contact-form").submit(function(e) {
e.preventDefault();
let name = $("#myInput").val();
jQuery.ajax({
method:'POST',
url: OBJ.ajaxurl,
data: {
'action':'getname', // This is our PHP function in the functions.php
'name' : name // This is the variable we are sending via AJAX
},
success:function(data) {
// This outputs the result of the ajax request (The Callback)
jQuery("#displayName").text( data );
},
error: function(errorThrown){
console.log(errorThrown);
}
});
});
})( jQuery );
This is where we make out AJAX in the front end. As you can see I have used an anonymous Jquery function. Inside this function, the form event submit
is handled and the Jquery ajax function is used to make the request. In WordPress, it is a safe practice to use jQuery instead of $ when referencing elements. While this article is not about how to use JQuery in WordPress, I will put relevant links in the resources section.
Add code to functions.php file.
Now add the following code to the functions.php( which should be in your child-theme root folder)
function contact_form_register_scripts() {
// to incldue the external script files
wp_enqueue_script( 'contact-script', get_stylesheet_directory_uri() . '/js/contact.js', array( 'jquery' ), false, true );
wp_localize_script(
'contact-script',
'OBJ',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))
);
}
add_action( 'wp_enqueue_scripts', 'contact_form_register_scripts' );
//access the data send with the Ajax call, and send the response
function getname() {
if( isset( $_REQUEST )){
$name = $_REQUEST['name'];
echo $name;
}
wp_die();// required to terminate immediately and return a proper response
}
//for execution in the admin area
add_action( 'wp_ajax_getname', 'getname' );
//executes for front-end users who are not logged in to the system.
add_action( 'wp_ajax_nopriv_getname', 'getname' );
wp_enqueue_script
()
wp_enqueue_script() is to enqueue scripts.
wp_enqueue_script( 'contact-script', get_stylesheet_directory_uri() . '/js/contact.js', array( 'jquery' ), false, true );
'contact-script'
is the handler, which should be a unique string so that WordPress can differentiate this script from any other enqueued scripts.
get_stylesheet_directory_uri() . '/js/contact.js'
set the path to the contact.js file
array( 'jquery' )
is the dependency array. We use JQuery in contact.js
The next argument I set to false
to avoid any compatibility issues. Setting this to false ensure that this script would use the version of the JQuery equal to the current WordPress that you have installed on your system.
a version number is automatically added equal to the current installed WordPress version.
The last argument is set to true
. This makes sure that the script will run before </body>
and not in the <head>
. This is critical to improve the performance of the website.
wp_localize_script
()
As you might be aware that PHP scripts can directly not pass values to Javascript scripts. Therefore, WordPress offers a special function called wp_localize_script(). Our AJAX call uses a URL to make the request. In wordpress, all the AJAX calls are made to admin-ajax.php. So, we need to pass this URL to admin-ajax.php to the script in contact.js.
wp_localize_script('contact-script','OBJ',array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));
'contact-script'
is the hander, which must be the same string you used in wp_enqueue_script()
'OBJ'
is the name of the object that we are going pass to contact.js
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ))
is the data we are passing in the Object. In this case, the URL to admin-ajax.php
. we have used this data as OBJ.ajaxurl
in the URL of the Jquery.ajax
function in contact.js
Handling AJAX requests in the backend
getname
is the function to handle the Ajax request in the backend. You can run this code in the admin area and for front-end users who are not logged in to the system.
add_action( 'wp_ajax_getname', 'getname' );
add_action( 'wp_ajax_nopriv_getname', 'getname' );
In the above statements, you must use the wp_ajax_
and wp_ajax_nopriv_
followed by a unique string, ideally, the name of the function that you are calling with the hook.
Resources
How To Properly Add jQuery Scripts To WordPress
Using ‘$’ instead of ‘jQuery’ in WordPress