WordPress environment
First of all, in order to achieve this goal, he recommended registering, then inserting a jQuery script into the queue, which will redirect the request to the server. These operations will hook into the wp_enqueue_scripts action hook. In the same hook, you should put wp_localize_script so that it includes arbitrary JavaScript. That way, a JS object will be available in front of it. This object contains the correct URL to be used by the jQuery descriptor.
Please take a look at:
Add them in the main plugin file.
add_action( 'wp_enqueue_scripts', 'so_enqueue_scripts' ); function so_enqueue_scripts(){ wp_register_script( 'ajaxHandle', get_template_directory() . 'PATH TO YOUR SCRIPT FILE', array(), false, true ); wp_enqueue_script( 'ajaxHandle' ); wp_localize_script( 'ajaxHandle', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin_ajax.php' ) ) ); }
File: jquery.ajax.js
This file calls the AJAX call.
jQuery(document).ready( function($){
Also add these files to the main plugin file.
Finally, in your functions.php file there should be a function called by an AJAX call. Remember the suffixes:
wp_ajax (enable function only for registered users or control panel operations)wp_ajax_nopriv (allow function for users without privileges)
These suffixes plus an action make up the name of your action:
wp_ajax_myaction or wp_ajax_nopriv_myaction
add_action( "wp_ajax_myaction", "so_wp_ajax_function" ); add_action( "wp_ajax_nopriv_myaction", "so_wp_ajax_function" ); function so_wp_ajax_function(){ //DO whatever you want with data posted //To send back a response you have to echo the result! echo $_POST['name']; echo $_POST['age']; wp_die(); // ajax call must die to avoid trailing 0 in your response }
source share