1. WORDPRESS & AJAX Presented by Ronald Huereca at WordCamp Philly 2010 Presentation online at: http://www.wpajax.com/code
2. Who Am I? - Author of the WordPress and Ajax e-book http://www.wpajax.com - Plugin author of Ajax Edit Comments http://www.ajaxeditcomments.com - WordPress developer at WebDevStudios http://www.webdevstudios.com And third most im P ortant person in WordPress (important with a capital P , dangit)
4. What is Ajax ? » What the heck does that mean? When you click on a rating, an event occurs The event and data is parsed and an Ajax request is sent The server processes the request, sends back a response, And the output is shown to the user
5.
6. WordPress and Ajax Foundation » Loading Scripts » wp_enqueue_script WordPress function: wp_enqueue_script prevents duplicate scripts and allows for a predictable loading order via dependencies <?php wp_enqueue_script ( 'handle', 'src', 'deps', 'ver', 'in_footer' ); ?> handle - Unique name for the script src - Location of the script deps - Array of dependencies (uses handler names) ver - Version of the script (string) in_footer - Load the scripts in the footer (boolean, default is false) wp_enqueue_script ( 'my_script', plugins_url ( 'my_plugin/my_script.js’ ), array ( 'jquery', 'another_script' ), '1.0.0', true );
7. WordPress and Ajax Foundation » Loading Scripts » wp_print_scripts WordPress action: wp_print_scripts allows you to print scripts for the front-end and admin area <?php add_action ( 'wp_print_scripts' , 'add_scripts' ) ; function add_scripts () { if ( is_admin () ) return ; wp_enqueue_script ( 'jquery ' ) ; } ?> Function name needs to be unique Loads jQuery on every front-end page
8. WordPress and Ajax Foundation » Loading Scripts » admin_print_scripts WordPress action: admin_print_scripts allows you to print scripts for admin area <?php add_action ( 'admin_print_scripts' , 'add_admin_scripts' ) ; function add_admin_scripts () { wp_enqueue_script ( 'jquery ' ) ; } ?> Function name needs to be unique Loads jQuery on every admin page
9. WordPress and Ajax Foundation » Script Localization » wp_localize_script WordPress function: wp_localize_script allows you to capture dynamic PHP data for use in JavaScript wp_localize_script ( 'javascript_handle' , 'javascript_object_name' , 'l10n' ) ; Object name to be created in JavaScript Same handler name used for wp_enqueue_script An associative array of localized strings
10. WordPress and Ajax Foundation » Script Localization » wp_localize_script WordPress function: wp_localize_script example <?php add_action ( 'wp_print_scripts' , 'add_scripts' ) ; function add_scripts (){ wp_enqueue_script ( 'wp_grins' , plugins_url ( 'wp-grins-lite/js/wp-grins.js' ) , array ( 'jquery' ) , 1 . 0 ) ; $localized_variables = array ( 'Ajax_Url' = > admin_url ( 'admin-ajax.php' ) , 'Location' = > 'post' , 'Manual' = > 'false' ) ; wp_localize_script ( 'wp_grins' , 'wpgrins' , $localized_variables ) ; } ?> Object name to be created in JavaScript Localized variables An associative array of localized strings
11. WordPress and Ajax Foundation » Script Localization » wp_localize_script WordPress function: wp_localize_script allows you to capture dynamic PHP data for use in JavaScript <script type= 'text/javascript' > /* <![CDATA[ */ var wpgrins = { Ajax_Url : "http://localhost:8888/ronalfy/wp-admin/admin-ajax.php", Location : "post", Manual : "false" } ; /* ]]> */ </script> <script type= 'text/javascript' src= 'http://localhost:8888/ronalfy/wp-content/plugins/wp-grins-lite/js/wp-grins.js?ver=1' ></script> The resulting HTML source: jQuery ( document ) .ready ( function () { alert ( wpgrins.Ajax_Url ) ; }) ; Localization used in JavaScript
12. WordPress and Ajax Foundation » Loading Styles » wp_enqueue_style WordPress function: wp_enqueue_style prevents duplicate styles and allows for a predictable loading order via dependencies <?php wp_enqueue_style ( 'handle' , 'src' , 'deps' , 'ver' , 'media' ) ; ?> handle - Unique name for the style src - Location of the style deps - Array of dependencies (uses handler names) ver - Version of the style (string) media - Media type the stylesheet is defined for (e.g., screen, print, all) wp_enqueue_style ( 'my_css' , plugins_url ( 'my_plugin/my_css.css' ) , array ( 'another_css_file' ) , '1.0.0' , 'screen' ) ;
13. WordPress and Ajax Foundation » Loading Styles » wp_print_styles WordPress action: wp_print_styles allows you to print styles for the front-end and admin area <?php add_action ( 'wp_print_styles' , 'my_styles_callback' ) ; function my_styles_callback () { wp_enqueue_style ( 'my_css' , plugins_url ( 'my_plugin/my_css.css' ) , array ( 'another_css_file' ) , '1.0.0' , 'screen' ) ; } ?> Function name needs to be unique
14. WordPress and Ajax Foundation » Loading Styles » admin_print_styles WordPress action: admin_print_styles allows you to print styles for the admin area <?php add_action ( 'admin_print_styles' , 'admin_styles_callback' ) ; function admin_styles_callback () { wp_enqueue_style ( 'my_css' , plugins_url ( 'my_plugin/my_css.css' ) , array ( 'another_css_file' ) , '1.0.0' , 'screen' ) ; } ?> Function name needs to be unique
15.
16. WordPress and Ajax Foundation » Page Detection » Front-end WordPress Conditionals quick functions that alert you to a specific page, post type, or area of the site is_home() - Are we on the home page? is_page() - Are we on a page template? is_single() - Are we on a post template? is_admin() - Are we in the admin area? comments_open() - Are comments open for a post? And much, much more: http://codex.wordpress.org/Conditional_Tags
17.
18. WordPress and Ajax Foundation » Page Detection » Admin Area WordPress actions: admin_print_scripts and admin_print_styles Page detection can be performed by adding the page name as a suffix for both actions - admin_print_scripts- suffix (e.g., admin_print_scripts- post.php ) - admin_print_styles- suffix (e.g., admin_print_styles- comment.php )
19. WordPress and Ajax Foundation » Page Detection » Admin Area Example: Adding a Script When Editing or Creating a Post uses post.php (when editing a post) and post-new.php (when creating a post) <?php add_action ( 'admin_print_scripts-post.php' , 'my_plugin_load_scripts' ) ; add_action ( 'admin_print_scripts-post-new.php' , 'my_plugin_load_scripts' ) ; function my_plugin_load_scripts () { if ( get_post_type () == 'post' ) wp_enqueue_script ( 'jquery' ) ; } ?> Please note that admin_print_scripts and admin_print_styles use the same suffix format.
20. WordPress and Ajax Foundation » Page Detection » Admin Area Example: Page Detection for a Settings Page <?php add_action ( 'admin_menu' , 'my_admin_menu' ) ; //Function to initialize the admin menu function my_admin_menu () { $page_hook = add_menu_page ( "My Plugin Name Options" , "My Plugin" , 'administrator' , 'my_plugin' , 'my_plugin_admin_settings' ) ; add_action ( "admin_print_scripts-$page_hook" , 'my_plugin_load_scripts' ) ; } //Build the admin menu interface function my_plugin_admin_settings () { echo "My Plugin Page" ; } //Load our scripts function my_plugin_load_scripts () { wp_enqueue_script ( 'jquery' ) ; } ?> When you add a menu page, the function returns a page hook you can use as a suffix for admin_print_scripts and admin_print_styles More menu hooks are available here: http://codex.wordpress.org/Adding_Administration_Menus
21. WordPress and Ajax Foundation » Admin Ajax WordPress action: wp_ajax <?php add_action ( 'wp_ajax_getcomment' , 'callback_function' ) ; add_action ( 'wp_ajax_nopriv_getcomment' , 'callback_function' ) ; function callback_function () { //process data and send Ajax response exit ; } ?> The wp_ajax WordPress action takes an Ajax action name (e.g., getcomment ) and optionally a nopriv suffix for users that aren’t logged in. More information: http://codex.wordpress.org/AJAX_in_Plugins The Ajax action is passed via JavaScript to admin-ajax.php , which alerts WordPress to run the callback function when the action is detected. A common mis-conception is that admin-ajax.php is used for just admin Ajax requests. You can use admin-ajax.php in non-admin areas as well.
22. WordPress and Ajax Foundation » admin-ajax.php WordPress file: wp-admin/admin-ajax.php The admin-ajax.php file is WordPress’ built-in Ajax processer.
24. WordPress and Ajax Foundation » WP_Ajax_Response XML Format <wp_ajax> <response action = "getcomment_0" > <getcomments id = "0" position = "1" > <response_data> <![CDATA[]]> </response_data> <supplemental> <awaiting_moderation> <![CDATA[0]]> </awaiting_moderation> <approved> <![CDATA[2,818]]> </approved> <spam> <![CDATA[636]]> </spam> <trashed> <![CDATA[0]]> </trashed> </supplemental> </getcomments> </response> </wp_ajax> The WP_Ajax_Response class sends back an XML document for use in JavaScript
25. WordPress and Ajax Foundation » WP_Ajax_Response » JavaScript Use JavaScript object: wpAjax Uses a script handler of wp-ajax-response wp_enqueue_script ( 'my_script' , get_stylesheet_directory_uri () . '/my_script.js' , array ( "jquery" , "wp-ajax-response" ) , "2.3" ) ; The wpAjax JavaScript class is useful for parsing the Ajax response The wp-ajax-response dependency
26. WordPress and Ajax Foundation » WP_Ajax_Response » JavaScript Use Example: wpAjax parsing in JavaScript var res = wpAjax.parseAjaxResponse ( ajax_response_data ,'ajax-response' ) ; Variable res now has a structure similar to:
27. WordPress and Ajax Foundation » WP_Ajax_Response » JavaScript Use Example: jQuery parsing of parsed data var res = wpAjax.parseAjaxResponse ( ajax_response_data ,'ajax-response' ) ; jQuery.each ( res.responses , function () { if (this .what == 'getcomments' ) { var moderation_count = this .supplemental.awaiting_moderation; var approved_count = this .supplemental.approved; var spam_count = this .supplemental.spam; var trashed_count = this .supplemental.trashed; } //end if }) ; //end each The wpAjax object makes it super easy to parse an Ajax response into variables
31. Ajax Registration Form » Class Structure Class structure for ajax-registration.php <?php class Ajax_Registration { //Constructors function Ajax_Registration () { $this -> __construct () ; } function __construct () { //actions and shortcode } //Add the registration script to a page function add_scripts () { } //Add Styles for the form function add_styles () { } function ajax_process_registration () { } //end ajax_process_registration //Perform shortcode page detection function has_shortcode () { } //Add/save shortcode information function post_save ( $post_id ) { } //end post_save //Print out the shortcode function rform_shortcode ( ) { } } //end class //Instantiate $ajaxregistration = new Ajax_Registration () ; ?>
38. Ajax Registration Form » Main Class » Add Styles Class method: add_styles Add the registration CSS file function add_styles () { if ( is_admin () || ! $this -> has_shortcode () ) return ; wp_enqueue_style ( 'ajax-registration-css' , plugins_url ( 'css/registration.css' , __FILE__ ) ) ; } Uses conditionals is_admin and has_shortcode for page detection. Will only load on the front-end where the shortcode exists in the page’s content.
39.
40.
41.
42. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Checking required entries We’ll use the WP_Error instance to add any errors if any fields are empty //Start data validation on firstname/lastname //Check required fields if ( empty ( $firstname ) ) $errors -> add ( 'firstname' , 'You must fill out a first name.' , 'firstname' ) ; if ( empty ( $lastname ) ) $errors -> add ( 'lastname' , 'You must fill out a last name.' ) ; if ( empty ( $username ) ) $errors -> add ( 'username' , 'You must fill out a user name.' ) ; if ( empty ( $email ) ) $errors -> add ( 'email' , 'You must fill out an e-mail address.' ) ; The first argument in $errors->add is an error code. However, the code also doubles for the form input ID that will be used in JavaScript.
43.
44.
45.
46.
47.
48.
49. Ajax Registration Form » Main Class » ajax_process_registration Sending the Ajax Response User has been created. Let’s send back an Ajax response. //Send back a response $success_response -> add ( array ( 'what' = > 'object' , 'data' = > 'User registration successful. Please check your e-mail.' )) ; $success_response -> send () ; exit ; } //end ajax_process_registration The data field in the Ajax response is used for sending a string message back to JavaScript. This message will be used in our form’s status area.
50. Ajax Registration Form » The CSS » registration.css Adding the CSS Code Code will go into the registration.css file #ajax-registration-list { list-style-type : none ; } #ajax-registration-list label { display : block ; } #ajax-registration-form .error { background-color : #FFEBE8 ; border : 1px solid #CC0000 ; } #ajax-registration-form .success { background-color : #FFFFE0 ; border : 1px solid #E6DB55 ; } Basic CSS is used here for the form layout and the error/status messages.
51.
52. Ajax Registration Form » The JavaScript » registration.js JavaScript function: init - Capturing the submit event The form has an ID of ajax-registration-form, which we’ll use to capture the submit event init : function () { $ ( "#ajax-registration-form" ) . submit ( function () { return false ; }) ; } The form ID ( ajax-registration-form ) is used with the jQuery submit event.
53.
54.
55.
56.
57. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The parsed data (if errors are detected)
58. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The errors data
59.
60. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Example Output If there are any errors, this is what you might see
61.
62. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Success Output If there aren’t any errors, this is what you might see
63. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Full Function Code function ( data ){ var res = wpAjax.parseAjaxResponse ( data , 'ajax-response' ) ; if ( res.errors ) { //form errors //re-enable submit button $ ( '#ajax-submit' ) .removeAttr ( "disabled" ) ; var html = '' ; $.each ( res.responses , function () { $.each (this .errors , function () { $ ( "#" + this .code ) .addClass ( 'error' ) ; html = html + this .message + '<br />' ; }) ; }) ; $ ( "#registration-status-message" ) .removeClass ( 'success' ) .addClass ( 'error' ) .html ( html ) ; } else { //no errors $.each ( res.responses , function () { $ ( "#registration-status-message" ) .addClass ( 'success' ) .html (this .data ) ; return ; }) ; } } Eat your heart out.
64. Conclusion » The Code Download link The sample Ajax registration form plugin can be found at: http://www.wpajax.com/code
65. Conclusion » Want to Know More? What to know more? Buy my damn book! http://www.wpajax.com
66. Conclusion » Want to Know More? What to know more? Buy my damn book! I mean, pretty please, buy my book. http://www.wpajax.com
67. Conclusion » WordPress and Ajax » The End - Twitter @ronalfy - Skype ronalfy - Personal site (rants and musings) http://www.ronalfy.com - WordPress and Ajax e-book http://www.wpajax.com That’s it! Thank you for your time. - Ajax Edit Comments http://www.ajaxeditcomments.com - WebDevStudios http://www.webdevstudios.com