xxxxxxxxxx
wp_enqueue_script(
'ajax-script',
plugins_url( '/js/myjquery.js', __FILE__ ),
array( 'jquery' ),
'1.0.,0',
true
);
xxxxxxxxxx
//the hook to use
add_action( 'wp_ajax_my_action', 'my_function' );
add_action( 'wp_ajax_nopriv_my_action', 'my_function' );
// the function to use
function my_function(){
// your code
}
xxxxxxxxxx
// Add this code to your theme's functions.php file or custom plugin
// Enqueue the necessary JavaScript file for AJAX
function enqueue_ajax_script() {
wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/ajax-script.js', array('jquery') );
// Pass the AJAX URL to the script
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'enqueue_ajax_script' );
// Process AJAX request
function process_ajax_request() {
// Handle the AJAX request logic here
// You can fetch data from the database, perform calculations, etc.
// You can use the WordPress functions and access the database through $wpdb
// For example, let's return a simple response
$response = array(
'message' => 'Hello from AJAX!'
);
// Send the response back to the client
wp_send_json( $response );
}
add_action( 'wp_ajax_my_ajax_action', 'process_ajax_request' );
add_action( 'wp_ajax_nopriv_my_ajax_action', 'process_ajax_request' );