WordPress Ajax: The Easy Way

Last Updated: January 29, 2019

This is a simple guide to implement an AJAX to your WordPress site.

Quick Summary:

  1. Register your Javascript file to WordPress and localize your AJAX admin URL.
  2. Setup simple jQuery script to send post to admin URL.
  3. We also need setup the action function to handle the request.

1) Register your Javascript file to WordPress and localize your AJAX admin URL

You may add it to your theme’s functions.php

// enqueue scripts
function enqueue_scripts() {
        // Enqueue Script
	wp_enqueue_script('script', get_stylesheet_directory_uri() . '/assets/js/script.js', array() ,null, true);
	
	// Localize the script with new data
	$translation_array = array(
		'ajaxURL' => admin_url( 'admin-ajax.php' )
	);
	wp_localize_script( 'script', 'src', $translation_array );
}
add_action( 'wp_enqueue_scripts', 'enqueue_scripts' );

I created a script.js located theme /assets/js/script.js. I localized AJAX URL using wp_location_script() functions

2) Setup simple jQuery script to send post to admin AJAX URL

jQuery(document).ready(function ($) {
   
    var ajaxURL = src.ajaxURL;
    var values = 'action=test_action&value=1';

    $.get(ajaxURL, values, function (response) {
                            
        $data = $.parseJSON(response);
        alert($data.status);
        
    });
  
});

3) We also need setup the action function to handle the request

add_action( 'wp_ajax_test_action', 'test_action' );
add_action( 'wp_ajax_nopriv_test_action', 'test_action' );

function test_action() {
    $response = array();

    $value = $_GET['value];

    // Add your script here, save database, etc

    $response['value] = $value;
    $response['status] = 'success';
    echo json_ecode($response);
    
    wp_die(); 
}

You can handle the values using $_GET or $_REQUEST method.

 

Add your feedback or comment below: