How to Load Ajax in Wordpress

How to Load Ajax in Wordpress

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Fixing Ajax Initialization in WordPress Child Themes

A common stumbling block for developers working with WordPress and custom themes involves initializing AJAX correctly within a child theme's functions.php. The goal is usually straightforward: load jQuery, enqueue your custom scripts, and hook up an action to handle requests. However, as the source material illustrates, simply adding wp_localize_script without understanding execution order often results in a cryptic browser error like ReferenceError: ajax_script is not defined.

The error occurs because the JavaScript variable ajax_script is not available at the time the event handler attempts to access it. In the provided code snippet, the developer registers the action add_action('template_redirect', 'add_ajax') but fails to ensure the script containing the localized data is actually enqueued before the page renders.

Enqueueing Scripts Before Localization

The core issue lies in the timing of script registration versus localization. WordPress does not automatically enqueue scripts just because you have added an action hook to template_redirect. You must explicitly call wp_enqueue_script to tell the system to load your custom JavaScript file into the page head or footer.

Without this explicit enqueue, the browser never requests the file that defines ajax_script. Consequently, when your jQuery code runs and tries to read ajax_script.ajaxurl, the variable remains undefined.

Here is the corrected approach for your functions.php:

// Enqueue your custom script first
wp_enqueue_script(
    'my-custom-ajax-script', 
    get_stylesheet_directory_uri() . '/assets/js/custom-ajax.js', // Ensure this file exists
    array('jquery'), 
    null, 
    true // Load in footer by default to prevent flash of unstyled content
);

// Localize the script after enqueueing
wp_localize_script(
    'my-custom-ajax-script', 
    'ajax_script', 
    array( 
        'ajaxurl' => admin_url('admin-ajax.php') 
    )
);

Handling Hooks and Template Loading

The code snippet also includes a require_once statement inside an action hook bound to template_redirect. While this is valid PHP logic, it can be confusing if not structured clearly. The function add_ajax is triggered on every front-end page load because of the template_redirect hook. This ensures that the localization happens immediately before any output is sent to the browser.

However, you must ensure that the AJAX handler itself is also registered correctly. The snippet uses:

add_action("wp_ajax_nopriv_function1", "function1");

Note that the second argument is a string "function1". If function1 is defined in an included file (ajax.php), this works. If you are using an anonymous function or a closure, you must pass the actual function name as a string or reference the closure directly.

Furthermore, ensure that the ajax.php file exists in the child theme directory path specified by $dirName. If that file does not exist or contains syntax errors, the page might throw a PHP fatal error before the JavaScript even executes. Always verify that your included files are valid and that the paths resolve correctly relative to the active theme.

Testing Your Setup

To confirm your AJAX setup is working without relying solely on Firebug (or the modern DevTools console), you can inspect the network tab in your browser's developer tools. Trigger the click event on your link. You should see a request fired to admin-ajax.php with the data {action: "function1"}.

If the request returns a 404 or 500 error, the PHP hook for wp_ajax_nopriv_function1 is likely not firing, or there is a fatal error in your included files. If the request fires but the response is empty, check your success callback logic and ensure the data you are echoing in the AJAX handler is being properly escaped using esc_html() to prevent XSS vulnerabilities.

Best Practices for Child Themes

When working with child themes, it is crucial to use get_stylesheet_directory_uri() for asset paths rather than get_template_directory_uri(). This ensures that your scripts load from the active child theme regardless of which parent theme is installed. Additionally, always prefix your custom script handles and function names to avoid collisions if you switch themes or merge codebases later.

If you are looking for a more robust way to handle complex frontend interactions, consider how modern frameworks abstract these details. For instance, Laravel offers a clean separation of concerns where routes and controllers handle AJAX logic explicitly, often eliminating the need for manual wp_localize_script calls by utilizing global variables defined in the view data or configuration files. While WordPress relies heavily on hooks and action filters to achieve similar results, understanding the execution order of enqueueing and localization remains the key to a stable implementation.

Our network