WordPress + AJAX = magix

Cole Geissinger
@colegeissinger
www.colegeissinger.com
 Web Developer
 

WHAT IS AJAX???

Asynchronous
Javascript
and
xml

Example


https://github.com/colegeissinger/wpsfo-ajax-august-2013



Enqueue Yo Scripts


ALWAYS use wp_enqueue_script


wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer )
  • $handle* - Unique ID for the script
  • $src - URL to the script
    • Themes - get_stylesheet_directory_uri() . 'PATH/HERE'
    • Plugins  - plugins_url( 'PATH/HERE', __FILE__ )
  • $deps - other script handles that are required (eg. jQuery)
  • $ver - The version of the script (blank = WP version)
  • $in_footer - add to wp_footer() in theme

hook with wp_enqueue_scripts



add_action( 'wp_enqueue_scripts', 'function_name' )

  • wp_enqueue_scripts is for enqueueing scripts
  • wp_print_scripts is fired when printing scripts
    DON'T USE WP_PRINT_SCRIPTS.
    Kittens cry when you do.
    And that's sad.

Localize



  • Use to add arbitrary JavaScript.
  • If adding to front-end, get the link to the 
    admin-ajax.php file in WordPress. 


Break it down


wp_localize_script( $handle, $object_name, $l10n );
  • $handle* - Should match the handle in wp_eqnueue_script
  • $object_name* - The namespace to contain our arbitrary JavaScript
  • $l10n* - The array which contains our Ajax URL and any other arbitrary JavaScript

The AJAX



Listen for a click event


Listen for a click on the submit button


The actual ajax!



Process the AJax request



Make sure everything is secure and was submitted



Return our new content








  • Return JSON for our JavaScript. Used in the "complete" function in our Ajax.
  • Always end your Ajax processor with die(); Other wise you'll get the number 0 added to your JSON.



The Final countdown









Two prefixes -
wp_ajax_ACTION_NAME - Ajax for logged in users
wp_ajax_nopriv_ACTION_NAME - Ajax for logged out users

Success!

Party time.



Questions? Comments? Cookies?








Get das slides! http://bit.ly/wpsfo-ajax







Cole Geissinger
@colegeissinger
www.colegeissinger.com

WordPress + Ajax = Magic

By Cole Geissinger

WordPress + Ajax = Magic

  • 4,017