Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Basic rigging for using AJAX in WordPress.
* This is the PHP function that is triggered from the JavaScript.
function callback() {
// Do a bunch of fancy stuff.
die(); // This is required for a proper response.
add_action( 'wp_ajax_script_handle', 'callback' ); // Hook for the WordPress Dashboard.
add_action( 'wp_ajax_script_handle_nopriv', 'callback' ); // Hook for the user facing side of the site.
* Register the scripts with WordPress
function register_scripts() {
wp_register_script( 'script-handle', $path_to_javascript_file, $dependencies, 'version', $in_footer = true );
wp_enqueue_script( 'script-handle' );
This is used to pass the URL of WordPress' AJAX stuff to the script. You can add more values to the array to pass more information.
wp_localize_script( 'script-handle', 'ObjectName', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'parameter' => $whatever_you_want_to_pass ) );
add_action( 'enqueue_scripts', 'register_scripts' );
jQuery( document ).ready( function ( $ ) {
var data = {
action: 'script_handle'
// You can add other data from the AJAX object passed in wp_localize_script() here.
// This can be placed inside an event also.
$.post( ObjectName.ajaxurl, data, function ( response ) {
// Place what ever JavaScript you need here.
} );
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment