Download presentation
Presentation is loading. Please wait.
1
Doing AJAX in WordPress
Micah Wood
2
Enqueuing Scripts wp_enqueue_script( $handle = 'ajax-yall',
$source = plugins_url( 'ajax.js', __FILE__ ), $dependencies = array( 'jquery' ), );
3
Use the Right Hook! Right: wp_enqueue_scripts Wrong: wp_print_scripts
wp_head
4
Passing Data to JavaScript
wp_localize_script( $handle = 'ajax-yall', $object_name = 'ajaxYall', $data = array( 'ajaxurl' => admin_url( 'admin-ajax.php' ), 'nonce' => wp_create_nonce( 'ajaxin-it' ), ) );
5
jQuery Makes Life Easy jQuery(document).ready(function($) {
// DO COOL STUFF });
6
Use the Best Request Type
// Fetch data $.get(); // Modify data $.post();
7
A Typical AJAX Request $('#my-element').click( function() { $.get(
ajaxYall.ajaxurl, { action: 'ajaxin-it', nonce: ajaxYall.nonce, postID: ID }, function( data, textStatus, jqXHR ) { if( jqXHR.status == 200 && textStatus == 'success' ) { // Do stuff } }, 'json' // Can also be xml, script, or html ); } );
8
WordPress AJAX Handling
$my_action = 'ajaxin-it'; if( defined( 'DOING_AJAX' ) && DOING_AJAX ) { // For logged in users add_action( 'wp_ajax_' . $my_action, 'do_stuff' ); // For logged out users add_action( 'wp_ajax_nopriv_' . $my_action, 'do_stuff' ); }
9
Respond to the Request <?php function do_stuff() {
if( wp_verify_nonce( $_GET['nonce'], 'ajaxin-it' ) ){
$response = array( 'status' => 'success', 'message' => "It's AJAX Y'all!", ); header( 'Content: application/json' ); echo json_encode( $response ); die; }
10
Questions
11
Get in Touch Micah Wood @wpscholar
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.