This post was last updated on June 4th, 2021 at 04:02 pm
In the WordPress backend, there is a global ajaxurl
variable defined by WordPress itself.
Whereas for the frontend, we have to define the variable by ourselves as it is not created by WP.
The function we use is called wp_localize_script
. It takes three arguments:
script-handler-name
, the registration handler of theajax-example.js
script.- A string that will act as a JavaScript object.
- An array, which contains the actual data we want to pass from our JavaScript.
So, if we write my_ajax_object.ajaxurl
, it will output the value of admin_url(‘admin-ajax.php’), in other words, the URL of the admin-ajax.php file. We’ll use it in the JavaScript part.
Let’s assume your AJAX calls are in ajax-example.js
file, then add wp_localize_script
for this JS file like so:
Example of WordPress AJAX in the frontend.
This will produce a JS alert box with the text 1044 when a page has been loaded in the administration panel. In the functions.php
file:
function theme_name_scripts() { wp_enqueue_script( 'script-handler-name', get_template_directory_uri() . '/js/ajax-example.js', array('jquery'), '1.0.0', true ); wp_localize_script( 'script-handler-name', 'my_ajax_object', array( // URL to wp-admin/admin-ajax.php which process the request 'ajaxurl' => admin_url( 'admin-ajax.php' ), // a nonce with a unique ID "myajax-nonce" // to check it later when an AJAX request is sent 'security' => wp_create_nonce( 'my-special-string' ) )); } add_action( 'wp_enqueue_scripts', 'theme_name_scripts' ); // Function that handles the AJAX request function my_action_callback() { check_ajax_referer( 'my-special-string', 'security' ); $whatever = intval( $_POST['whatever'] ); $whatever += 10; echo $whatever; die(); // required to return a proper result } add_action( 'wp_ajax_my_action', 'my_action_callback' );
In the ajax-example.js
file:
jQuery(document).ready(function($) { var data = { action: 'my_action', security : my_ajax_object.security, whatever: 1234 }; // ajaxurl is always defined in the admin header and points to admin-ajax.php $.post(my_ajax_object.ajaxurl, data, function(response) { alert('This is return from the server: ' + response); }); });
Leave A Reply