Skip to content

Instantly share code, notes, and snippets.

@jessekanner
Created November 11, 2021 20:22
Show Gist options
  • Select an option

  • Save jessekanner/f9473f384707c98389b4a1c893b85419 to your computer and use it in GitHub Desktop.

Select an option

Save jessekanner/f9473f384707c98389b4a1c893b85419 to your computer and use it in GitHub Desktop.
WordPress Basic Ajax Handling
Requirements
-------------------------
In wp-admin you do not need to do anything, the js library is always loaded
In the front-end you need to enqueue the script wp-util, like this:
add_action( 'wp_enqueue_scripts', 'my_enqueue_function' );
function my_enqueue_function() {
// Option 1: Manually enqueue the wp-util library.
wp_enqueue_script( 'wp-util' );
// Option 2: Make wp-util a dependency of your script (usually better).
wp_enqueue_script( 'my-script', 'my-script.js', [ 'wp-util' ] );
}
The JS Library
---------------------------
The wp-util script contains the wp.ajax object that you can use to make ajax requests:
wp.ajax.post( action, data ).done( okCallback ).fail( errCallback )
Your example:
wp.ajax.post( "get_data", {} )
.done(function(response) {
alert("Your vote could not be added");
alert(response);
});
PHP code
----------------------------
Of course, you still need to create the wp_ajax_* hooks in your PHP script.
add_action( 'wp_ajax_nopriv_get_data', 'my_ajax_handler' );
add_action( 'wp_ajax_get_data', 'my_ajax_handler' );
function my_ajax_handler() {
wp_send_json_success( 'It works' );
}
Tip:
For Ajax responses WordPress provides two functions:
wp_send_json_success( $my_data ) and wp_send_json_error( $my_data )
both functions return a JSON object and instantly terminate the request (i.e., they exit;)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment