This gist show you how to create a function for handling ajax request.
Last active
January 24, 2017 03:27
-
-
Save ariona/98edd2476b708e3429b4 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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' ); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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