AJAX the WordPress way

843 views
750 views

Published on

Published in: Technology
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
843
On SlideShare
0
From Embeds
0
Number of Embeds
2
Actions
Shares
0
Downloads
8
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

AJAX the WordPress way

  1. 1. AJAX the WordPress way● Justin Foell● WordPress Developer @ 9seeds.com● justin@9seeds.com● @justinfoell
  2. 2. What is AJAX?● Asynchronous JavaScript and XML● A fast way of getting data or a portion of a page from the web server w/o having to do a full page request
  3. 3. How does AJAX work (in WordPress)?● jQuery makes an AJAX call to the server from your browser● WordPress routes the call appropriately● The call is processed by WordPress core - or a theme or plugin - which returns HTML or JSON (JavaScript Object Notation) data● Returned data is displayed appropriately
  4. 4. Required Pieces● JavaScript (and form) on to trigger an AJAX call● WordPress hook (wp_ajax_* action) to route the request● A function to handle the request and return the expected result
  5. 5. Dirty Details Getting JavaScript/jQuery loaded● Register & Enqueue your JavaScript using wp_register_script & wp_enqueue_script● Remember to include jquery as a dependency when registering your script, so it automagically gets loaded● Use wp_localize_script to expose WordPress variables to JavaScript – such as the ajax submit URL (only needed for Front-End AJAX)● AJAX calls always go to admin_url( admin-ajax.php ) regardless if theyre made from the front-end or wp- admin
  6. 6. Dirty Details (cont.) JavaScript/jQuery AJAX call● Use jQuery AJAX Shorthand Methods● The data object should have a member variable called action – the value of it will correspond to the WordPress action executed...
  7. 7. Dirty Details (cont.) WordPress ajax hook add_action( wp_ajax_<action-value>, function_to_run_on_ajax_call );● Should return valid HTML or JSON data● You MUST exit or die!!!111one
  8. 8. WordPress Admin Example● Almost the same as the front-end example● Hook form into an existing page or add your form to a custom wp-admin page● Register & Enqueue javascript● ajaxurl is already set● Use json_encode in WordPress● Use jQuery.parseJSON in jQuery
  9. 9. Questions???
  10. 10. Thank you!● Justin Foell – Developer @ 9seeds.com● justin@9seeds.com Resources:● api.jquery.com/category/ajax/shorthand-methods● codex.wordpress.org/AJAX_in_Plugins● Code: bit.ly/jf-wordup-2012● Slides: bit.ly/jf-slides-wordup-2012

×