How To Effectively Implement Ajax in WordPress

The concept of AJAX or Asynchronous JavaScript and XML is fascinating. The way it works and how it dynamically ease the web pages is also beneficial to almost every dynamic sites today. However, most people have a misconception regarding Ajax. It is important to know that Ajax is neither a programming language nor a tool, but simply a technique which interacts dynamically to load multiple pages without any refresh using JavaScript. AJAX can be defined as “a technique of exchanging data with a server by updating the web pages without refreshing the whole page“. In this tutorial, we are going to implement AJAX in WordPress step by step. Or let’s say we are going to create a simple Subscription Form using AJAX in WordPress.

Before proceeding further, let us have a brief concept regarding the importance of AJAX in WordPress.

Importance of Ajax in WordPress

  • Increase Speed: The major purpose of the ajax is to improve the speed and performance of the website. The great example of Ajax is Facebook Like Button. A person likes the button without refreshing the page and it will be saved to the database without the reload of the website.
  • User-Friendly: Since the ajax improves the performance and speed of the web application, the user feels easy to use and navigate.
  • Can be used in Multiple Pages: Single callback of Ajax can be used in multiple pages of the website. This saves the time as well as multiple calling of files.

Implementing Ajax In WordPress

Ajax In WordPress

There are various ways of using Ajax in WordPress. Meaning, you can use Ajax via different techniques. Here, we will take an example of simple subscription form to use Ajax. The user will enter their email address and the admin will get the subscription mail address via mail.

Here’s the HTML Subscription Form

Implement the below HTML Form wherever necessary. You can either create a custom template page or use in sidebar widget.

mustBeWebForm">

In the above code, we have the Form ID mustBeWebForm and ajaxHandler sendMessage which we are going to use later. Besides that, the form is normal.

<input type="hidden" name="action" value="subscribe"/>

Using the hidden input field above, we are going to pass the Ajax value in the script below.

Here’s the custom_scripts.js

Add the following script in your custom script.

jQuery('#mustBeWebForm').submit(ajaxSubmit);
  function ajaxSubmit(){
  var mustBeWebFormData = jQuery(this).serialize();
  jQuery.ajax({
  type:"POST",
  url: "/wp-admin/admin-ajax.php",
  data: mustBeWebFormData,
  success:function(data){
  jQuery("#feedback").html(data);
  jQuery("#mustBeWebForm")[0].reset();
  }
   });
 return false;
}

In the above lines of code, we did nothing other than submitting our Form ID mustBeWebForm and serializing the Ajax data via mustBeWebFormData variable. The above script will work only if we implement code to handle Ajax call in functions.php file of our theme.

Note: Do not forget to enqueue the script in functions.php as

wp_enqueue_script( ‘custom_scripts’, get_template_directory_uri() . ‘/js/custom_scripts.js’, array(), ”, true );

Code to Handle Ajax Call

This is the final Step. This is the part where we control our Ajax along with the form data. Insert the below code in your theme’s functions.php.

function subscribe(){
   global $wpdb;
   $email = $_POST['email'];
   $subscribe = 'Email: '.$email;
   $to = 'subscribe@mustbeweb.com'; // put your email here
   $headers = 'From:Mustbeweb <info@mustbeweb.com>' . "\r\n"; 
   $subject = 'Subscription form';

   if(wp_mail($to, $subject, $subscribe, $headers)===FALSE){
    echo "Error in submitting your Request";
   }
   else {
    echo "You have successfully Subsribed !!";
   }
   die();
}
add_action('wp_ajax_subscribe', 'subscribe');
add_action('wp_ajax_nopriv_subscribe', 'subscribe'); // not really needed

This is it. We have successfully implemented Ajax in WordPress with simple Subscription Form. So what we did in the above code ? We linked the page templates, scripts, and action function with each other to form a single Ajax Call. \

Also Read:   How to Enable Coming Soon Page and Maintenance Mode for WordPress Website

To explain in brief, each request needs to provide at least one piece of data (either using POST or Get Method) called action. And based on the action, the code in admin-ajax.php will create two hooks. wp_ajax_subscribe and wp_ajax_nopriv_subscribe, where subscribe is the value of the GET or POST variable action.

As mentioned earlier, there are multiple ways of using Ajax in WordPress. We have used the simple yet effective way to handle AJAX. If you follow the above code thoroughly, it will work like a charm. You can always customize according to your requirements. If this article helped you in anyway, do not forget to hit the share button below.

The following two tabs change content below.

Prabin Parajuli

Tech-Blogger, Web Enthusiast
Prabin Parajuli is a Web Developer, Blogger, freelance writer, and a pet lover. He also loves to travel a lot.

Latest posts by Prabin Parajuli (see all)

Share This Post