Skip to content

Instantly share code, notes, and snippets.

@ariona
Last active January 24, 2017 03:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ariona/98edd2476b708e3429b4 to your computer and use it in GitHub Desktop.
Save ariona/98edd2476b708e3429b4 to your computer and use it in GitHub Desktop.

WordPress Admin Ajax Request Handle Function

This gist show you how to create a function for handling ajax request.

<?php
// This line if where the theme enqueue the main script
wp_enqueue_script( 'ajax-script', get_template_directory_uri().'/script.js', array('jquery') );
// Add this line to localize ajax_url
wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
// Function to handle ajax request
function my_action(){
$result = array("This","is","ajax","result");
wp_send_json( $result );
}
// Register the action to wp_ajax. Notice the tag naming, wp_ajax_[function_name]
add_action( 'wp_ajax_my_action', 'my_action' );
// This line will register the action for nonpreveledge/nonlogin user
add_action( 'wp_ajax_nopriv_my_action', 'my_action' );
/*
ajax_object.ajax_url will be availabel since we localize it on the function.php
*/
$.get( ajax_object.ajax_url, {
// Registered action
action: 'my_action',
// Add query string here if available. for example
userid: '123',
}, function( result ){
console.log( result )
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment