Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
AJAX the WordPress way
1. AJAX the WordPress way
●
Justin Foell
●
WordPress Developer @ 9seeds.com
●
justin@9seeds.com
●
@justinfoell
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. 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. 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. 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 they're made from the front-end or wp-
admin
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. 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. 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