SlideShare a Scribd company logo
WORDPRESS & AJAX Presented by Ronald Huereca at WordCamp Philly 2010 Presentation online at:  http://www.wpajax.com/code
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)
What is Ajax?
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
WordPress and Ajax Foundation » What is needed? Load scripts and styles properly Use JavaScript Localization (to capture dynamic PHP content) Use Page Detection Know the WP Ajax actions and classes
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 );
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
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
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
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
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 :   &quot;http://localhost:8888/ronalfy/wp-admin/admin-ajax.php&quot;, Location :   &quot;post&quot;, Manual :   &quot;false&quot; } ; /* ]]> */   </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
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' ) ;
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
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
WordPress and Ajax Foundation » Page Detection What is page detection? Allows scripts and styles to load only when needed. Why is page detection important? Helps loading time Prevents script and style conflicts It’s just the right thing to do
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
WordPress and Ajax Foundation » Page Detection » Front-end Example:  Loading Scripts Only When There are Comments <?php add_action ( 'wp_print_scripts' ,  'my_plugin_load_scripts' ) ; function  my_plugin_load_scripts ()   { global  $post; if   (   ! (  is_single ()   ||  is_page ()   )   ||   !is_object ( $post )   ||   $post -> comment_count == 0  )   return ; wp_enqueue_script ( 'jquery' ) ; } ?> Makes sure we’re on a post or a page Checks for the existence of the $post object (needed to get the comment count) Checks that there are comments on a post or page
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 )
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.
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 (   &quot;My Plugin Name Options&quot; ,  &quot;My Plugin&quot; ,  'administrator' ,  'my_plugin' ,  'my_plugin_admin_settings' ) ; add_action ( &quot;admin_print_scripts-$page_hook&quot; ,  'my_plugin_load_scripts' ) ; } //Build the admin menu interface function  my_plugin_admin_settings ()   { echo   &quot;My Plugin Page&quot; ; } //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
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.
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.
WordPress and Ajax Foundation » WP_Ajax_Response WordPress class:  WP_Ajax_Response <?php add_action ( 'wp_ajax_getcomment' ,  'callback_function' ) ; add_action ( 'wp_ajax_nopriv_getcomment' ,  'callback_function' ) ;   function  callback_function ()   { $comment_count = wp_count_comments () ; $response =  new  WP_Ajax_Response () ; $response -> add ( array ( 'what'  = >   'getcomments' , 'supplemental'  = >   array ( 'awaiting_moderation'  = >   number_format ( $comment_count -> moderated ) , 'approved'  = >   number_format ( $comment_count -> approved ) , 'spam'  = >   number_format ( $comment_count -> spam ) , 'trashed'  = >   number_format ( $comment_count -> trash ) ) )) ; $response -> send () ; exit ; } ?> The  WP_Ajax_Response  class is useful for returning a XML-formatted document back into JavaScript for parsing.  It’s extremely useful.
WordPress and Ajax Foundation » WP_Ajax_Response XML Format <wp_ajax> <response   action = &quot;getcomment_0&quot; > <getcomments   id = &quot;0&quot;   position = &quot;1&quot; > <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
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 ( &quot;jquery&quot; ,  &quot;wp-ajax-response&quot; )  ,  &quot;2.3&quot; ) ; The  wpAjax  JavaScript class is useful for parsing the Ajax response The wp-ajax-response dependency
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:
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
Ajax Registration Form Let’s create an Ajax registration form
Ajax Registration Form » Features Features we want A shortcode for inserting the form on a post or page Page detection for the shortcode No page re-loads (uses Ajax) Data validation is done via Ajax Error messages are shown via Ajax User is notified by e-mail when the registration has succeeded
Ajax Registration Form » Plugin File Structure Registration form will be written as a plugin ajax-registration.php (main plugin file) registration.js (our script file) registration.css (the plugin’s styles)
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 () ; ?>
Ajax Registration Form » Main Class » The Constructor  The class constructor will add all the actions and shortcode callbacks we need function  __construct ()   { //add scripts add_action (   'wp_print_scripts' ,  array (   & $this,  'add_scripts'   )   ) ; //add css add_action (   'wp_print_styles' ,  array (   & $this,  'add_styles'   )   ) ; //ajax add_action (   'wp_ajax_nopriv_submitajaxregistration' ,  array (   & $this,  'ajax_process_registration'   )   ) ; add_action (   'wp_ajax_submitajaxregistration' ,  array (   & $this,  'ajax_process_registration'   )   ) ; //when saving a post add_action (   'save_post' ,  array (   & $this,  'post_save'   )   ) ; //shortcode add_shortcode (   'rform' ,  array (   & $this,  'rform_shortcode'   )   ) ; } The  wp_print_scripts  and  wp_print_styles  actions are used for scripts and styles respectively The  wp_ajax  actions are used for a JavaScript action of  submitajaxregistration The  save_post  action will be used to assist us in page detection A shortcode of  rform  is created, with a callback method of  rform_shortcode
Ajax Registration Form » Main Class » Shortcode Creation Class method:  rform_shortcode Returns the form data as a string function  rform_shortcode (   )   { $return =  &quot;<form id='ajax-registration-form'>&quot; ; $return  . = wp_nonce_field (   'submit_ajax-registration' ,  '_registration_nonce' ,  true ,  false   ) ; $return  . =  &quot;<ul id='ajax-registration-list'>&quot; ;  $return  . =  &quot;<li><label for='firstname'>First name: </label><input type='text' size='30' name='firstname'  id='firstname' /></li>&quot; ; $return  . =  &quot;<li><label for='lastname'>Last name: </label><input type='text' size='30' name='lastname'  id='lastname' /></li>&quot; ; $return  . =  &quot;<li><label for='username'>Desired Username: </label><input type='text' size='30' name='username'  id='username' /></li>&quot; ; $return  . =  &quot;<li><label for='email'>E-mail Address: </label><input type='text' size='30' name='email'  id='email' /></li>&quot; ; $return  . =  &quot;<li><input type='submit' value='Submit Registration' name='ajax-submit'  id='ajax-submit' /></li>&quot; ; $return  . =  &quot;<li id='registration-status-message'></li>&quot; ; $return  . =  &quot;</ul>&quot; ; $return  . =  &quot;</form>&quot; ;   return  $return; } Nonce action name of _registration_nonce (will be verified later) Form ID of ajax-registration-form (used in JavaScript) Input IDs and names of firstname, lastname, username, email (used in JavaScript) Status message ID of registration-status-message (used in JavaScript)
Ajax Registration Form » Main Class » Shortcode Creation Adding the shortcode to a post
Ajax Registration Form » Main Class » Page Detection Class method:  post_save Find out if the post has the rform shortcode, and set a custom field if so function  post_save (  $post_id  )   { //Retrieve the post object - If a revision, get the original post ID $revision = wp_is_post_revision (  $post_id  ) ; if   (  $revision  ) $post_id = $revision; $post = get_post (  $post_id  ) ;   //Perform a test for a shortcode in the post's content preg_match ( '/\[rform[^\]]*\]/is' , $post -> post_content, $matches ) ;      if   (   count (  $matches  )  == 0  )   { delete_post_meta (  $post_id,  '_ajax_registration'   ) ; }   else   { update_post_meta (  $post_id,  '_ajax_registration' ,  '1'   ) ; } }   //end post_save Retrieve the original post ID if a revision Test the post content for the shortcode  rform If the shortcode is present, set the  _ajax_registration  custom field.  If not, remove it.
Ajax Registration Form » Main Class » Page Detection Class method:  has_shortcode A conditional that lets us know if the post has the rform shortcode or not //Returns true if a post has the rform shortcode, false if not function  has_shortcode ()   { global  $post; if   (   !is_object ( $post )   )   return   false ;  if   (  get_post_meta (  $post -> ID,  '_ajax_registration' ,  true   )   )   return   true ; else return   false ; } Checks for a custom field of  _ajax_registration . If the custom field exists, return  true .  If not, return  false .
Ajax Registration Form » Main Class » Add Scripts and Localization Class method:  add_scripts Add the registration script file and some JavaScript localization //Add the registration script to a page function  add_scripts ()   { if   (  is_admin ()   ||   ! $this -> has_shortcode ()   )   return ; wp_enqueue_script (   'ajax-registration-js' ,  plugins_url (   'js/registration.js'  , __FILE__   ) ,  array (   'jquery' ,  'wp-ajax-response'   ) ,  '1.0'   ) ; wp_localize_script (   'ajax-registration-js' ,  'ajaxregistration' ,  array (   'Ajax_Url'  = >  admin_url (   'admin-ajax.php'   )   )   ) ; } 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. Localizes a JavaScript object of  ajaxregistration  with a variable called  Ajax_Url .  Ajax_Url  points to WordPress’  admin-ajax.php , which we’ll need to make our Ajax request in JavaScript.
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.
Ajax Registration Form » Main Class » The Ajax Processor Class method:  ajax_process_registration Processes the Ajax request and returns an Ajax response function  ajax_process_registration ()   { //Verify the nonce check_ajax_referer (   'submit_ajax-registration'   ) ;   exit ;   }   //end ajax_process_registration The first thing we do in the Ajax processor is check the passed nonce. The nonce is checked with  check_ajax_referer .  The nonce action named  submit_ajax-registration  was set in the  rform_shortcode  method.  The JavaScript file is responsible for setting a  $_POST  variable called  _ajax_nonce , which is what  check_ajax_referer  checks for.
Ajax Registration Form » Main Class » ajax_process_registration Parsing the data //Need registration.php for data validation require_once (  ABSPATH  .  WPINC  .   '/registration.php' ) ;   //Get post data if   (   !isset (   $_POST [ 'ajax_form_data' ]   )   )   die ( &quot;-1&quot; ) ; parse_str (   $_POST [ 'ajax_form_data' ] , $form_data  ) ; The WordPress file  registration.php  is included (includes such functions as  validate_username  and  username_exists ) Checks for  $_POST  variable  ajax_form_data  (the JavaScript file will set this variable) Parses the data into the  $form_data  array via  parse_str $form_data['firstname'] $form_data['lastname'] $form_data['email'] $form_data['username']
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Sanitizing the entries Uses the sanitize_text_field function to sanitize the form inputs //Get the form fields $firstname = sanitize_text_field (  $form_data [ 'firstname' ]   ) ; $lastname = sanitize_text_field (  $form_data [ 'lastname' ]   ) ; $username = sanitize_text_field (  $form_data [ 'username' ]   ) ; $email = sanitize_text_field (  $form_data [ 'email' ]   ) ;   $error_response = $success_response =  new  WP_Ajax_Response () ; $errors =  new  WP_Error () ; Uses the sanitize_text_field WordPress function to sanitize the form inputs Instantiates an instance of WP_Ajax_Response (for sending the Ajax responses) Instantiates an instance of WP_Error (used as part of the Ajax response)
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.
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: If any errors, send a response We’ll be using the WP_Ajax_Response instance to return a response if errors are present //If required fields aren't filled out, send response if   (   count   (  $errors -> get_error_codes ()   )   >  0  )   { $error_response -> add ( array ( 'what'  = >   'errors' , 'id'  = >  $errors )) ; $error_response -> send () ; exit ; } The  WP_Error   get_error_codes  method is used to determine if there are any errors saved If there are errors, we build the Ajax response using fields  what  and  id The  id  portion allows for a  WP_Error  object
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Check for a valid username //Add usernames we don't want used $invalid_usernames =  array (   'admin'   ) ; //Do username validation $username = sanitize_user (  $username  ) ; if   (   ! validate_username (  $username  )   ||   in_array (  $username, $invalid_usernames  )   )   { $errors -> add (   'username' ,  'Username is invalid.'   ) ; } if   (  username_exists (  $username  )   )   { $errors -> add (   'username' ,  'Username already exists.'   ) ; } Username is further sanitized via the  sanitize_user  WordPress function The  $invalid_usernames  array can contain usernames you don’t want users to select. If the username isn’t valid (via the  validate_username  function) or a username is reserved, we add an error - If the username already exists (via the  username_exists  function), we add an error
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Check for a valid e-mail address //Do e-mail address validation if   (   ! is_email (  $email  )   )   { $errors -> add (   'email' ,  'E-mail address is invalid.'   ) ; } if   ( email_exists ( $email ))   { $errors -> add (   'email' ,  'E-mail address is already in use.'   ) ; } If the e-mail address is invalid (via the  is_email  function), we add an error If the e-mail address already exists (via the  email_exists  function), we add an error
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: If any further errors, send a response We’ll be using the WP_Ajax_Response instance to return a response if errors are present //If required fields aren't filled out, send response if   (   count   (  $errors -> get_error_codes ()   )   >  0  )   { $error_response -> add ( array ( 'what'  = >   'errors' , 'id'  = >  $errors )) ; $error_response -> send () ; exit ; } We have to assume that all fields aren’t empty at this point Only invalid username/email errors will be sent
Ajax Registration Form » Main Class » ajax_process_registration Create the User Object All data has been validated.  Create the User object. //Everything has been validated, proceed with creating the user //Create the user $user_pass = wp_generate_password () ; $user =  array ( 'user_login'  = >  $username, 'user_pass'  = >  $user_pass, 'first_name'  = >  $firstname, 'last_name'  = >  $lastname, 'user_email'  = >  $email ) ; $user_id = wp_insert_user (  $user  ) ; A user password is generated (via  wp_generate_password ) A  $user  array is created with fields  user_login ,  user_pass ,  first_name ,  last_name , and  user_email User is created by passing the  $user  array to function  wp_insert_user Function  wp_insert_user  returns the new user’s ID
Ajax Registration Form » Main Class » ajax_process_registration Send the Registration E-mail User has been created.  Send a registration e-mail. /*Send e-mail to admin and new user -  You could create your own e-mail instead of using this function*/ wp_new_user_notification (  $user_id, $user_pass  ) ; A user e-mail is sent by passing the variables  $user_id  and  $user_pass  to the  wp_new_user_notification  function You could skip this step and instead create a custom e-mail (using  wp_mail )
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.
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.
Ajax Registration Form » The JavaScript » registration.js JavaScript structure A jQuery namespace called registrationform is used jQuery ( document ) .ready ( function ()   { var  $  =  jQuery; $.registrationform  =   { init :  function ()   {     } } ;  //end .registrationform $.registrationform.init () ; }) ; - A jQuery object named  registrationform  is created Within the  registrationform  object, a there is a placeholder function named init The function is initialized by calling  $.registrationform.init
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 ()   {   $ ( &quot;#ajax-registration-form&quot; ) . submit ( function ()   { return   false ; }) ; } The form ID ( ajax-registration-form ) is used with the jQuery  submit  event.
Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Clearing any error messages In the event the form has previously been submitted, we’ll need to clear all previous messages $ ( &quot;#ajax-registration-form&quot; ) . submit ( function ()   { //Clear all form errors $ ( '#ajax-registration-form input' ) .removeClass ( 'error' ) ; //Update status message $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'error' ) .addClass ( 'success' ) .html ( 'Sending...' ) ; //Disable submit button $ ( '#ajax-submit' ) .attr ( &quot;disabled&quot;,   &quot;disabled&quot; ) ;   return   false ; }) ; All form inputs are cleared of errors (by removing the  error  CSS class) The status message (with ID of  registration-status-message ) is updated with the  success  CSS class and given the text “Sending…” The  submit  button (with ID  ajax-submit ) is disabled so the user can’t click it again during the submission process
Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Parse the Form Data We’ll use jQuery to parse the form data into a string we can pass via Ajax //Disable submit button $ ( '#ajax-submit' ) .attr ( &quot;disabled&quot;,   &quot;disabled&quot; ) ; //Serialize form data var  form_data  =  $ ( '#ajax-registration-form input' ) .serializeArray () ; form_data  =  $.param ( form_data ) ;   return   false ; All form inputs are captured and serialized to an array via the  serializeArray  function The serialized form data is then converted to a url-encoded string via the  param  function. The form_data variable now has a value similar to:  _registration_nonce=0ca8be2b7b&firstname=Ronald&lastname=Huereca&username=ronalfy&email=ron%40ronalfy.com
Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Submit the Ajax Request form_data  =  $.param ( form_data ) ;   //Submit ajax request $.post (  ajaxregistration.Ajax_Url ,   {   action :   'submitajaxregistration',   ajax_form_data :  form_data ,   _ajax_nonce :  $ ( '#_registration_nonce' ) .val ()   } , function ( data ){ //Success code goes here } ) ; return   false ; The jQuery post function acts as an Ajax POST event We pass it the URL to WordPress’  admin-ajax.php  file (via localized JavaScript variable  ajaxregistration.Ajax_Url ) The Ajax action  submitajaxregistration  is used for the WordPress  wp_ajax  action A post variable named  ajax_form_data  contains all our form data A post variable named  _ajax_nonce  contains the form’s nonce Finally, a callback method is created to handle the Ajax response (the response will be held in the  data  variable)
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response function ( data ){ var  res  =  wpAjax.parseAjaxResponse ( data ,   'ajax-response' ) ; if   ( res.errors )   { //errors }   else   { //no errors } } Data is parsed via the  parseAjaxResponse  function If errors are detected, spit out errors If no errors are detected, display a success mesage
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The parsed data (if errors are detected)
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The errors data
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The errors data Iterate through each response, and iterate through each error within the response if   ( res.errors )   { //form errors //re-enable submit button $ ( '#ajax-submit' ) .removeAttr ( &quot;disabled&quot; ) ; var  html  =   '' ; $.each ( res.responses ,  function ()   { $.each (this .errors ,  function ()   { $ ( &quot;#&quot;   +   this .code ) .addClass ( 'error' ) ; html  =  html  +   this .message  +   '<br />' ; }) ; }) ; $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'success' ) .addClass ( 'error' ) .html ( html ) ; } There could be multiple responses, so we iterate through each one Within each response are several errors, so we iterate through those and build an HTML string with all of the error messages Furthermore, since each error has a code that identifies the form  input , we add an  error  class (via CSS) to show that there is an error Finally, we update our status message with the errors
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Example Output If there are any errors, this is what you might see
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Success If there are no errors, we parse the data in the success portion of the conditional }   else   { //no errors $.each ( res.responses ,  function ()   { $ ( &quot;#registration-status-message&quot; ) .addClass ( 'success' ) .html (this .data ) ; return ; }) ; } There could be multiple responses, so we iterate through each one Output the success message (via the this.data variable)
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
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 ( &quot;disabled&quot; ) ; var  html  =   '' ; $.each ( res.responses ,  function ()   { $.each (this .errors ,  function ()   { $ ( &quot;#&quot;   +   this .code ) .addClass ( 'error' ) ; html  =  html  +   this .message  +   '<br />' ; }) ; }) ; $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'success' ) .addClass ( 'error' ) .html ( html ) ; }   else   { //no errors $.each ( res.responses ,  function ()   { $ ( &quot;#registration-status-message&quot; ) .addClass ( 'success' ) .html (this .data ) ; return ; }) ; } } Eat your heart out.
Conclusion » The Code Download link The sample Ajax registration form plugin can be found at:  http://www.wpajax.com/code
Conclusion » Want to Know More? What to know more?  Buy my damn book! http://www.wpajax.com
Conclusion » Want to Know More? What to know more?  Buy my damn book!  I mean, pretty please, buy my book. http://www.wpajax.com
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

More Related Content

PPT
High Performance Ajax Applications
PDF
Ajax Security
PDF
How to make Ajax work for you
PDF
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
PDF
Keypoints html5
PPTX
jQuery from the very beginning
KEY
Mobile HTML, CSS, and JavaScript
PDF
HTML5: friend or foe (to Flash)?
High Performance Ajax Applications
Ajax Security
How to make Ajax work for you
Realize mais com HTML 5 e CSS 3 - 16 EDTED - RJ
Keypoints html5
jQuery from the very beginning
Mobile HTML, CSS, and JavaScript
HTML5: friend or foe (to Flash)?

What's hot (20)

PDF
jQuery UI and Plugins
PDF
jQuery Proven Performance Tips & Tricks
PDF
HTML5 for the Silverlight Guy
KEY
HTML5 vs Silverlight
PDF
Building a JavaScript Library
PDF
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
PDF
HTML 5 - Overview
PDF
Create responsive websites with Django, REST and AngularJS
PDF
[Bristol WordPress] Supercharging WordPress Development
PPT
Writing Pluggable Software
PPTX
The Django Web Application Framework 2
PDF
Design patterns revisited with PHP 5.3
PDF
High-Quality JavaScript
PPTX
End-to-end testing with geb
PDF
High Performance Ajax Applications
PDF
What you need to know bout html5
PDF
SocketStream
PDF
Performance, Games, and Distributed Testing in JavaScript
PDF
High Performance JavaScript - WebDirections USA 2010
PDF
HTML5 JavaScript APIs
jQuery UI and Plugins
jQuery Proven Performance Tips & Tricks
HTML5 for the Silverlight Guy
HTML5 vs Silverlight
Building a JavaScript Library
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
HTML 5 - Overview
Create responsive websites with Django, REST and AngularJS
[Bristol WordPress] Supercharging WordPress Development
Writing Pluggable Software
The Django Web Application Framework 2
Design patterns revisited with PHP 5.3
High-Quality JavaScript
End-to-end testing with geb
High Performance Ajax Applications
What you need to know bout html5
SocketStream
Performance, Games, and Distributed Testing in JavaScript
High Performance JavaScript - WebDirections USA 2010
HTML5 JavaScript APIs
Ad

Viewers also liked (20)

PDF
Nate Reist WCGR WP AJAX presentation
PDF
Tutorial beacon full_200815
PPTX
The Water Energy and Food Security Nexus - is it really new?
PDF
numerical analysis
PDF
Water-Food-Energy Nexus in the context of groundwater use in India: Experienc...
PDF
[Ronald p. morash] bridge to abstract mathematics
DOCX
Image processing (Signal Processing)
PPT
Proof in Mathematics
PPT
CEU lecture 2 2016
PPT
MedSpring: the Nexus Water-Energy-Food (W-E-F) to strengthen the EU-Mediterr...
PPT
CEU lecture 3 2016
PPTX
Agricultural Productivity and Economic Development in Southern Africa
PPTX
Drupal - A Web Based Content Management System
PPT
Irrigation suitability in Malawi
PPTX
Modeling the water-energy-food nexus in the Indus River of Pakistan
PPTX
Selecting a content management system
PPT
Solving Equations
PPTX
Early warning systems for food water-energy nexus in GMS region
PDF
Behavioral Economics and the Design of Agricultural Index Insurance in Develo...
PPS
Selecting A Content Management System For Athabasca University
Nate Reist WCGR WP AJAX presentation
Tutorial beacon full_200815
The Water Energy and Food Security Nexus - is it really new?
numerical analysis
Water-Food-Energy Nexus in the context of groundwater use in India: Experienc...
[Ronald p. morash] bridge to abstract mathematics
Image processing (Signal Processing)
Proof in Mathematics
CEU lecture 2 2016
MedSpring: the Nexus Water-Energy-Food (W-E-F) to strengthen the EU-Mediterr...
CEU lecture 3 2016
Agricultural Productivity and Economic Development in Southern Africa
Drupal - A Web Based Content Management System
Irrigation suitability in Malawi
Modeling the water-energy-food nexus in the Indus River of Pakistan
Selecting a content management system
Solving Equations
Early warning systems for food water-energy nexus in GMS region
Behavioral Economics and the Design of Agricultural Index Insurance in Develo...
Selecting A Content Management System For Athabasca University
Ad

Similar to WordPress and Ajax (20)

PDF
JavaScript & AJAX in WordPress
PPT
WordPress as a Content Management System
PPTX
Using WordPress as your application stack
PPT
WordPress development paradigms, idiosyncrasies and other big words
PDF
Avinash Kundaliya: Javascript and WordPress
PDF
WCLA12 JavaScript
PPTX
Introduction to Plugin Programming, WordCamp Miami 2011
PPTX
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
PPT
Sxsw 20090314
PPT
Google在Web前端方面的经验
PPT
SXSW: Even Faster Web Sites
ODP
Widgets: Making Your Site Great and Letting Others Help - WordCamp Victoria
PPTX
Childthemes ottawa-word camp-1919
ODP
Exploring Symfony's Code
PDF
WordPress as the Backbone(.js)
PPT
How Not to Build a WordPress Plugin
PPT
Php frameworks
PPTX
Fast by Default
PPT
symfony & jQuery (phpDay)
PPTX
Wp meetup custom post types
JavaScript & AJAX in WordPress
WordPress as a Content Management System
Using WordPress as your application stack
WordPress development paradigms, idiosyncrasies and other big words
Avinash Kundaliya: Javascript and WordPress
WCLA12 JavaScript
Introduction to Plugin Programming, WordCamp Miami 2011
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
Sxsw 20090314
Google在Web前端方面的经验
SXSW: Even Faster Web Sites
Widgets: Making Your Site Great and Letting Others Help - WordCamp Victoria
Childthemes ottawa-word camp-1919
Exploring Symfony's Code
WordPress as the Backbone(.js)
How Not to Build a WordPress Plugin
Php frameworks
Fast by Default
symfony & jQuery (phpDay)
Wp meetup custom post types

More from Ronald Huereca (6)

PPTX
Introduction to React for jQuery Developers
PDF
How to Successfully Take Over a WordPress Plugin
PPTX
Designing Plugins for Release
KEY
WordPress Must-Use Plugins (Quick Overview)
KEY
WordPress Multisite General Overview
PDF
WordPress Plugin Localization
Introduction to React for jQuery Developers
How to Successfully Take Over a WordPress Plugin
Designing Plugins for Release
WordPress Must-Use Plugins (Quick Overview)
WordPress Multisite General Overview
WordPress Plugin Localization

Recently uploaded (20)

PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PPTX
OMC Textile Division Presentation 2021.pptx
PPTX
A Presentation on Artificial Intelligence
PDF
Mushroom cultivation and it's methods.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Machine Learning_overview_presentation.pptx
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Network Security Unit 5.pdf for BCA BBA.
PDF
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PPT
Teaching material agriculture food technology
PPTX
TLE Review Electricity (Electricity).pptx
PDF
Approach and Philosophy of On baking technology
PPTX
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
Group 1 Presentation -Planning and Decision Making .pptx
Per capita expenditure prediction using model stacking based on satellite ima...
Building Integrated photovoltaic BIPV_UPV.pdf
OMC Textile Division Presentation 2021.pptx
A Presentation on Artificial Intelligence
Mushroom cultivation and it's methods.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Machine Learning_overview_presentation.pptx
MIND Revenue Release Quarter 2 2025 Press Release
Network Security Unit 5.pdf for BCA BBA.
Video forgery: An extensive analysis of inter-and intra-frame manipulation al...
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Teaching material agriculture food technology
TLE Review Electricity (Electricity).pptx
Approach and Philosophy of On baking technology
TechTalks-8-2019-Service-Management-ITIL-Refresh-ITIL-4-Framework-Supports-Ou...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Diabetes mellitus diagnosis method based random forest with bat algorithm
Group 1 Presentation -Planning and Decision Making .pptx

WordPress and Ajax

  • 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. WordPress and Ajax Foundation » What is needed? Load scripts and styles properly Use JavaScript Localization (to capture dynamic PHP content) Use Page Detection Know the WP Ajax actions and classes
  • 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 : &quot;http://localhost:8888/ronalfy/wp-admin/admin-ajax.php&quot;, Location : &quot;post&quot;, Manual : &quot;false&quot; } ; /* ]]> */   </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. WordPress and Ajax Foundation » Page Detection What is page detection? Allows scripts and styles to load only when needed. Why is page detection important? Helps loading time Prevents script and style conflicts It’s just the right thing to do
  • 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. WordPress and Ajax Foundation » Page Detection » Front-end Example: Loading Scripts Only When There are Comments <?php add_action ( 'wp_print_scripts' , 'my_plugin_load_scripts' ) ; function my_plugin_load_scripts () { global $post; if ( ! ( is_single () || is_page () ) || !is_object ( $post ) || $post -> comment_count == 0 ) return ; wp_enqueue_script ( 'jquery' ) ; } ?> Makes sure we’re on a post or a page Checks for the existence of the $post object (needed to get the comment count) Checks that there are comments on a post or page
  • 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 ( &quot;My Plugin Name Options&quot; , &quot;My Plugin&quot; , 'administrator' , 'my_plugin' , 'my_plugin_admin_settings' ) ; add_action ( &quot;admin_print_scripts-$page_hook&quot; , 'my_plugin_load_scripts' ) ; } //Build the admin menu interface function my_plugin_admin_settings () { echo &quot;My Plugin Page&quot; ; } //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.
  • 23. WordPress and Ajax Foundation » WP_Ajax_Response WordPress class: WP_Ajax_Response <?php add_action ( 'wp_ajax_getcomment' , 'callback_function' ) ; add_action ( 'wp_ajax_nopriv_getcomment' , 'callback_function' ) ;   function callback_function () { $comment_count = wp_count_comments () ; $response = new WP_Ajax_Response () ; $response -> add ( array ( 'what' = > 'getcomments' , 'supplemental' = > array ( 'awaiting_moderation' = > number_format ( $comment_count -> moderated ) , 'approved' = > number_format ( $comment_count -> approved ) , 'spam' = > number_format ( $comment_count -> spam ) , 'trashed' = > number_format ( $comment_count -> trash ) ) )) ; $response -> send () ; exit ; } ?> The WP_Ajax_Response class is useful for returning a XML-formatted document back into JavaScript for parsing. It’s extremely useful.
  • 24. WordPress and Ajax Foundation » WP_Ajax_Response XML Format <wp_ajax> <response action = &quot;getcomment_0&quot; > <getcomments id = &quot;0&quot; position = &quot;1&quot; > <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 ( &quot;jquery&quot; , &quot;wp-ajax-response&quot; ) , &quot;2.3&quot; ) ; 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
  • 28. Ajax Registration Form Let’s create an Ajax registration form
  • 29. Ajax Registration Form » Features Features we want A shortcode for inserting the form on a post or page Page detection for the shortcode No page re-loads (uses Ajax) Data validation is done via Ajax Error messages are shown via Ajax User is notified by e-mail when the registration has succeeded
  • 30. Ajax Registration Form » Plugin File Structure Registration form will be written as a plugin ajax-registration.php (main plugin file) registration.js (our script file) registration.css (the plugin’s styles)
  • 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 () ; ?>
  • 32. Ajax Registration Form » Main Class » The Constructor The class constructor will add all the actions and shortcode callbacks we need function __construct () { //add scripts add_action ( 'wp_print_scripts' , array ( & $this, 'add_scripts' ) ) ; //add css add_action ( 'wp_print_styles' , array ( & $this, 'add_styles' ) ) ; //ajax add_action ( 'wp_ajax_nopriv_submitajaxregistration' , array ( & $this, 'ajax_process_registration' ) ) ; add_action ( 'wp_ajax_submitajaxregistration' , array ( & $this, 'ajax_process_registration' ) ) ; //when saving a post add_action ( 'save_post' , array ( & $this, 'post_save' ) ) ; //shortcode add_shortcode ( 'rform' , array ( & $this, 'rform_shortcode' ) ) ; } The wp_print_scripts and wp_print_styles actions are used for scripts and styles respectively The wp_ajax actions are used for a JavaScript action of submitajaxregistration The save_post action will be used to assist us in page detection A shortcode of rform is created, with a callback method of rform_shortcode
  • 33. Ajax Registration Form » Main Class » Shortcode Creation Class method: rform_shortcode Returns the form data as a string function rform_shortcode ( ) { $return = &quot;<form id='ajax-registration-form'>&quot; ; $return . = wp_nonce_field ( 'submit_ajax-registration' , '_registration_nonce' , true , false ) ; $return . = &quot;<ul id='ajax-registration-list'>&quot; ; $return . = &quot;<li><label for='firstname'>First name: </label><input type='text' size='30' name='firstname' id='firstname' /></li>&quot; ; $return . = &quot;<li><label for='lastname'>Last name: </label><input type='text' size='30' name='lastname' id='lastname' /></li>&quot; ; $return . = &quot;<li><label for='username'>Desired Username: </label><input type='text' size='30' name='username' id='username' /></li>&quot; ; $return . = &quot;<li><label for='email'>E-mail Address: </label><input type='text' size='30' name='email' id='email' /></li>&quot; ; $return . = &quot;<li><input type='submit' value='Submit Registration' name='ajax-submit' id='ajax-submit' /></li>&quot; ; $return . = &quot;<li id='registration-status-message'></li>&quot; ; $return . = &quot;</ul>&quot; ; $return . = &quot;</form>&quot; ;   return $return; } Nonce action name of _registration_nonce (will be verified later) Form ID of ajax-registration-form (used in JavaScript) Input IDs and names of firstname, lastname, username, email (used in JavaScript) Status message ID of registration-status-message (used in JavaScript)
  • 34. Ajax Registration Form » Main Class » Shortcode Creation Adding the shortcode to a post
  • 35. Ajax Registration Form » Main Class » Page Detection Class method: post_save Find out if the post has the rform shortcode, and set a custom field if so function post_save ( $post_id ) { //Retrieve the post object - If a revision, get the original post ID $revision = wp_is_post_revision ( $post_id ) ; if ( $revision ) $post_id = $revision; $post = get_post ( $post_id ) ;   //Perform a test for a shortcode in the post's content preg_match ( '/\[rform[^\]]*\]/is' , $post -> post_content, $matches ) ;     if ( count ( $matches ) == 0 ) { delete_post_meta ( $post_id, '_ajax_registration' ) ; } else { update_post_meta ( $post_id, '_ajax_registration' , '1' ) ; } } //end post_save Retrieve the original post ID if a revision Test the post content for the shortcode rform If the shortcode is present, set the _ajax_registration custom field. If not, remove it.
  • 36. Ajax Registration Form » Main Class » Page Detection Class method: has_shortcode A conditional that lets us know if the post has the rform shortcode or not //Returns true if a post has the rform shortcode, false if not function has_shortcode () { global $post; if ( !is_object ( $post ) ) return false ; if ( get_post_meta ( $post -> ID, '_ajax_registration' , true ) ) return true ; else return false ; } Checks for a custom field of _ajax_registration . If the custom field exists, return true . If not, return false .
  • 37. Ajax Registration Form » Main Class » Add Scripts and Localization Class method: add_scripts Add the registration script file and some JavaScript localization //Add the registration script to a page function add_scripts () { if ( is_admin () || ! $this -> has_shortcode () ) return ; wp_enqueue_script ( 'ajax-registration-js' , plugins_url ( 'js/registration.js' , __FILE__ ) , array ( 'jquery' , 'wp-ajax-response' ) , '1.0' ) ; wp_localize_script ( 'ajax-registration-js' , 'ajaxregistration' , array ( 'Ajax_Url' = > admin_url ( 'admin-ajax.php' ) ) ) ; } 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. Localizes a JavaScript object of ajaxregistration with a variable called Ajax_Url . Ajax_Url points to WordPress’ admin-ajax.php , which we’ll need to make our Ajax request in JavaScript.
  • 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. Ajax Registration Form » Main Class » The Ajax Processor Class method: ajax_process_registration Processes the Ajax request and returns an Ajax response function ajax_process_registration () { //Verify the nonce check_ajax_referer ( 'submit_ajax-registration' ) ;   exit ;   } //end ajax_process_registration The first thing we do in the Ajax processor is check the passed nonce. The nonce is checked with check_ajax_referer . The nonce action named submit_ajax-registration was set in the rform_shortcode method. The JavaScript file is responsible for setting a $_POST variable called _ajax_nonce , which is what check_ajax_referer checks for.
  • 40. Ajax Registration Form » Main Class » ajax_process_registration Parsing the data //Need registration.php for data validation require_once ( ABSPATH . WPINC . '/registration.php' ) ;   //Get post data if ( !isset ( $_POST [ 'ajax_form_data' ] ) ) die ( &quot;-1&quot; ) ; parse_str ( $_POST [ 'ajax_form_data' ] , $form_data ) ; The WordPress file registration.php is included (includes such functions as validate_username and username_exists ) Checks for $_POST variable ajax_form_data (the JavaScript file will set this variable) Parses the data into the $form_data array via parse_str $form_data['firstname'] $form_data['lastname'] $form_data['email'] $form_data['username']
  • 41. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Sanitizing the entries Uses the sanitize_text_field function to sanitize the form inputs //Get the form fields $firstname = sanitize_text_field ( $form_data [ 'firstname' ] ) ; $lastname = sanitize_text_field ( $form_data [ 'lastname' ] ) ; $username = sanitize_text_field ( $form_data [ 'username' ] ) ; $email = sanitize_text_field ( $form_data [ 'email' ] ) ;   $error_response = $success_response = new WP_Ajax_Response () ; $errors = new WP_Error () ; Uses the sanitize_text_field WordPress function to sanitize the form inputs Instantiates an instance of WP_Ajax_Response (for sending the Ajax responses) Instantiates an instance of WP_Error (used as part of the Ajax response)
  • 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. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: If any errors, send a response We’ll be using the WP_Ajax_Response instance to return a response if errors are present //If required fields aren't filled out, send response if ( count ( $errors -> get_error_codes () ) > 0 ) { $error_response -> add ( array ( 'what' = > 'errors' , 'id' = > $errors )) ; $error_response -> send () ; exit ; } The WP_Error get_error_codes method is used to determine if there are any errors saved If there are errors, we build the Ajax response using fields what and id The id portion allows for a WP_Error object
  • 44. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Check for a valid username //Add usernames we don't want used $invalid_usernames = array ( 'admin' ) ; //Do username validation $username = sanitize_user ( $username ) ; if ( ! validate_username ( $username ) || in_array ( $username, $invalid_usernames ) ) { $errors -> add ( 'username' , 'Username is invalid.' ) ; } if ( username_exists ( $username ) ) { $errors -> add ( 'username' , 'Username already exists.' ) ; } Username is further sanitized via the sanitize_user WordPress function The $invalid_usernames array can contain usernames you don’t want users to select. If the username isn’t valid (via the validate_username function) or a username is reserved, we add an error - If the username already exists (via the username_exists function), we add an error
  • 45. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Check for a valid e-mail address //Do e-mail address validation if ( ! is_email ( $email ) ) { $errors -> add ( 'email' , 'E-mail address is invalid.' ) ; } if ( email_exists ( $email )) { $errors -> add ( 'email' , 'E-mail address is already in use.' ) ; } If the e-mail address is invalid (via the is_email function), we add an error If the e-mail address already exists (via the email_exists function), we add an error
  • 46. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: If any further errors, send a response We’ll be using the WP_Ajax_Response instance to return a response if errors are present //If required fields aren't filled out, send response if ( count ( $errors -> get_error_codes () ) > 0 ) { $error_response -> add ( array ( 'what' = > 'errors' , 'id' = > $errors )) ; $error_response -> send () ; exit ; } We have to assume that all fields aren’t empty at this point Only invalid username/email errors will be sent
  • 47. Ajax Registration Form » Main Class » ajax_process_registration Create the User Object All data has been validated. Create the User object. //Everything has been validated, proceed with creating the user //Create the user $user_pass = wp_generate_password () ; $user = array ( 'user_login' = > $username, 'user_pass' = > $user_pass, 'first_name' = > $firstname, 'last_name' = > $lastname, 'user_email' = > $email ) ; $user_id = wp_insert_user ( $user ) ; A user password is generated (via wp_generate_password ) A $user array is created with fields user_login , user_pass , first_name , last_name , and user_email User is created by passing the $user array to function wp_insert_user Function wp_insert_user returns the new user’s ID
  • 48. Ajax Registration Form » Main Class » ajax_process_registration Send the Registration E-mail User has been created. Send a registration e-mail. /*Send e-mail to admin and new user - You could create your own e-mail instead of using this function*/ wp_new_user_notification ( $user_id, $user_pass ) ; A user e-mail is sent by passing the variables $user_id and $user_pass to the wp_new_user_notification function You could skip this step and instead create a custom e-mail (using wp_mail )
  • 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. Ajax Registration Form » The JavaScript » registration.js JavaScript structure A jQuery namespace called registrationform is used jQuery ( document ) .ready ( function () { var $ = jQuery; $.registrationform = { init : function () {   } } ; //end .registrationform $.registrationform.init () ; }) ; - A jQuery object named registrationform is created Within the registrationform object, a there is a placeholder function named init The function is initialized by calling $.registrationform.init
  • 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 () { $ ( &quot;#ajax-registration-form&quot; ) . submit ( function () { return false ; }) ; } The form ID ( ajax-registration-form ) is used with the jQuery submit event.
  • 53. Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Clearing any error messages In the event the form has previously been submitted, we’ll need to clear all previous messages $ ( &quot;#ajax-registration-form&quot; ) . submit ( function () { //Clear all form errors $ ( '#ajax-registration-form input' ) .removeClass ( 'error' ) ; //Update status message $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'error' ) .addClass ( 'success' ) .html ( 'Sending...' ) ; //Disable submit button $ ( '#ajax-submit' ) .attr ( &quot;disabled&quot;, &quot;disabled&quot; ) ;   return false ; }) ; All form inputs are cleared of errors (by removing the error CSS class) The status message (with ID of registration-status-message ) is updated with the success CSS class and given the text “Sending…” The submit button (with ID ajax-submit ) is disabled so the user can’t click it again during the submission process
  • 54. Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Parse the Form Data We’ll use jQuery to parse the form data into a string we can pass via Ajax //Disable submit button $ ( '#ajax-submit' ) .attr ( &quot;disabled&quot;, &quot;disabled&quot; ) ; //Serialize form data var form_data = $ ( '#ajax-registration-form input' ) .serializeArray () ; form_data = $.param ( form_data ) ; return false ; All form inputs are captured and serialized to an array via the serializeArray function The serialized form data is then converted to a url-encoded string via the param function. The form_data variable now has a value similar to: _registration_nonce=0ca8be2b7b&firstname=Ronald&lastname=Huereca&username=ronalfy&email=ron%40ronalfy.com
  • 55. Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Submit the Ajax Request form_data = $.param ( form_data ) ; //Submit ajax request $.post ( ajaxregistration.Ajax_Url , { action : 'submitajaxregistration', ajax_form_data : form_data , _ajax_nonce : $ ( '#_registration_nonce' ) .val () } , function ( data ){ //Success code goes here } ) ; return false ; The jQuery post function acts as an Ajax POST event We pass it the URL to WordPress’ admin-ajax.php file (via localized JavaScript variable ajaxregistration.Ajax_Url ) The Ajax action submitajaxregistration is used for the WordPress wp_ajax action A post variable named ajax_form_data contains all our form data A post variable named _ajax_nonce contains the form’s nonce Finally, a callback method is created to handle the Ajax response (the response will be held in the data variable)
  • 56. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response function ( data ){ var res = wpAjax.parseAjaxResponse ( data , 'ajax-response' ) ; if ( res.errors ) { //errors } else { //no errors } } Data is parsed via the parseAjaxResponse function If errors are detected, spit out errors If no errors are detected, display a success mesage
  • 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. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The errors data Iterate through each response, and iterate through each error within the response if ( res.errors ) { //form errors //re-enable submit button $ ( '#ajax-submit' ) .removeAttr ( &quot;disabled&quot; ) ; var html = '' ; $.each ( res.responses , function () { $.each (this .errors , function () { $ ( &quot;#&quot; + this .code ) .addClass ( 'error' ) ; html = html + this .message + '<br />' ; }) ; }) ; $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'success' ) .addClass ( 'error' ) .html ( html ) ; } There could be multiple responses, so we iterate through each one Within each response are several errors, so we iterate through those and build an HTML string with all of the error messages Furthermore, since each error has a code that identifies the form input , we add an error class (via CSS) to show that there is an error Finally, we update our status message with the errors
  • 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. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Success If there are no errors, we parse the data in the success portion of the conditional } else { //no errors $.each ( res.responses , function () { $ ( &quot;#registration-status-message&quot; ) .addClass ( 'success' ) .html (this .data ) ; return ; }) ; } There could be multiple responses, so we iterate through each one Output the success message (via the this.data variable)
  • 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 ( &quot;disabled&quot; ) ; var html = '' ; $.each ( res.responses , function () { $.each (this .errors , function () { $ ( &quot;#&quot; + this .code ) .addClass ( 'error' ) ; html = html + this .message + '<br />' ; }) ; }) ; $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'success' ) .addClass ( 'error' ) .html ( html ) ; } else { //no errors $.each ( res.responses , function () { $ ( &quot;#registration-status-message&quot; ) .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