Ajax (Asynchronous JavaScript and XML) is a set of web development techniques that allow for the creation of dynamic and interactive web applications. The key feature of Ajax is the ability to update parts of a web page without requiring a full page reload.

This is achieved by using a combination of JavaScript, HTML, and CSS to send and receive data to and from a web server in the background, without interfering with the user’s interaction with the page. This makes web pages feel more responsive and can improve the user experience.

Ajax can be used for a wide range of applications, including real-time updates, auto-saving of form data, and interactive search features. It is a powerful tool for creating web applications that feel fast and seamless to use.

Enqueue the necessary JavaScript files

To use AJAX in WordPress, you need to enqueue the necessary JavaScript files. You can enqueue the files using the wp_enqueue_script() function.

function prefix_ajax_enqueue() {

  wp_enqueue_script('prefix-main', get_template_directory_uri() . '/js/main.js', array('jquery'), '1.0.0', true);

}
add_action( 'wp_enqueue_scripts', 'prefix_ajax_enqueue' );

AJAX Url

The WordPress admin AJAX URL is typically found in the admin-ajax.php file located in the root directory of your WordPress installation.

Nonce

A WordPress nonce (which stands for “number used once”) is a security feature used to prevent unauthorized access to certain WordPress actions or functions. It is a unique token generated by WordPress that is used to verify that a particular user has permission to perform a specific action or access certain data.

Localize Scripts

wp_localize_script() is a function in WordPress that allows you to pass data from the server side to the client side of your WordPress site. It is commonly used to pass variables and data from PHP to JavaScript, and is often used to make AJAX calls and other dynamic client-side functionality possible.

We will pass ajaxUrl and nonce using this function to JavaScript. This function is also added inside wp_enqueue_scripts action hook.

wp_localize_script('prefix-main', 'prefixObj', array(
  'ajaxUrl' => admin_url('admin-ajax.php'),
  'nonce' => wp_create_nonce('prefix_ajax_nonce'),
) );

Prepare your AJAX action

You need to prepare your AJAX action and register it with WordPress. To register your AJAX action, use the wp_ajax_ hook. This hook allows you to bind your custom function to the WordPress AJAX API.

function prefix_ajax_request() {

  // Check if the nonce is valid.
  check_ajax_referer('prefix_ajax_nonce', 'nonce');

  // The $_POST will contain all the data sent via ajax
  if ( isset($_POST) ) {
   
    $data = $_POST['data'];

    // your main functionality here...
   
  }

  // Pass data response back to ajax
  echo wp_json_encode([
    'data' => $data
  ]);

  // Always die in functions echoing ajax content
  wp_die();

}
add_action( 'wp_ajax_prefix_ajax_request', 'prefix_ajax_request' );

// If you wanted to also use the function for non-logged in users (in a theme for example)
add_action( 'wp_ajax_nopriv_prefix_ajax_request', 'prefix_ajax_request' );

Create a JavaScript file

Create a JavaScript file in your theme or plugin with the name you enqueued earlier. This file should contain the necessary JavaScript code to make an AJAX call.

Make the AJAX call

Using the JavaScript code, you can now make an AJAX call to the WordPress AJAX API. To do this, you will need to define the action and pass in the necessary data. Let run the AJAX when a button with id #my-button is clicked.

Handle the AJAX response

Once the AJAX call is made, you will need to handle the response. Depending on the type of AJAX call, you may need to update the DOM or display a message.

$('#my-button').on('click', function(){

  $.ajax({
    url: prefixObj.ajaxUrl,
    method: 'POST',
    dataType: 'json',
    data: {
      action: 'prefix_ajax_request',
      data: 'data',
      nonce: prefixObj.nonce
    },
    success: function(response) {
      // Handle the response from the server
    }
  });

});

Muhammad Zohaib

Web Developer specializing in WordPress to develop custom themes, plugins, troubleshooting technical issues and ensuring websites are optimized for search engines and meet accessibility standards. Currently working as Lead Developer at XeCreators.

Leave a Reply

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


The reCAPTCHA verification period has expired. Please reload the page.