Doing AJAX in WordPress Micah Wood / @wpscholar
Enqueuing Scripts wp_enqueue_script( $handle = 'ajax-yall', $source = plugins_url( 'ajax.js', __FILE__ ), $dependencies = array( 'jquery' ), );
Use the Right Hook! Right: wp_enqueue_scripts Wrong: wp_print_scripts wp_head
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' ), ) );
jQuery Makes Life Easy jQuery(document).ready(function($) { // DO COOL STUFF });
Use the Best Request Type // Fetch data $.get(); // Modify data $.post();
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 ); } );
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' ); }
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; }
Questions
Get in Touch Micah Wood @wpscholar http://micahwood.me