What is Ajax?
Ajax stands for Asynchronous JavaScript And XML. It’s used to create dynamic web applications. With Ajax, you don’t have to wait for the web page to reload to see a change. Everything’s taken care of automatically in the background without disrupting.
Intro to Ajax in WordPress
The core of WordPress already uses Ajax, but only in the admin screens. For instance, when you’re moderating comments or adding/deleting items from categories or posts, you can see instant updates thanks to Ajax. It’s also the tech behind the much loved auto-save functionality.
Here’s what the process for using Ajax in WordPress looks like:
- The user triggers an Ajax request, which is first passed to the admin-ajax.php file in the wp-admin folder.
- The Ajax request needs to supply at least one piece of data (using the GET or POST method). This request is called the action.
- The code in admin-ajax.php uses the action to create two hooks: wp_ajax_youraction and wp_ajax_nopriv_youraction. Here, your action is the value of the GET or POST variable action.
- The first hook wp_ajax_youraction executes only for logged-in users, while the second hook wp_ajax_nopriv_youraction caters exclusively for logged-out users. If you want to target all users, you need to fire them both separately.
Steps to run ajax in wordpress :
- First enquee you custom js file and initlize your custom ajax object in function.php which exist inside the your active theme.
<?php add_action( 'wp_enqueue_scripts', 'my_enqueue' ); function my_enqueue($hook) { wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery') ); // in JavaScript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ),) ); } // Same handler function... add_action( 'wp_ajax_my_action', 'my_action' ); function my_action() { global $wpdb; echo $_POST['data'] wp_die(); }
2 .
In your custom js file my_query.js file you need to add code which call the method “my_action() ” in function.php
jQuery(document).ready(function($) { var data = { 'action': 'my_action', 'data': 123 // We pass php values differently! }; // We can also pass the url value separately from ajaxurl for front end AJAX implementations jQuery.post(ajax_object.ajax_url, data, function(response) { alert('Got this from the server: ' + response); }); });