SlideShare una empresa de Scribd logo
1 de 67
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? ,[object Object],[object Object],[object Object],[object Object]
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? ,[object Object],[object Object],[object Object]
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' ) ; } ?> ,[object Object],[object Object],[object Object]
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 ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
Ajax Registration Form » Plugin File Structure Registration form will be written as a plugin ,[object Object],[object Object],[object Object]
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'   )   ) ; } ,[object Object],[object Object],[object Object],[object Object]
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; } ,[object Object],[object Object],[object Object],[object Object]
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 ,[object Object],[object Object],[object Object]
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 ; } ,[object Object],[object Object]
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'   )   )   ) ; } ,[object Object],[object Object]
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 ,[object Object],[object Object],[object Object],[object Object]
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  ) ; ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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 () ; ,[object Object],[object Object],[object Object]
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 ; } ,[object Object],[object Object],[object 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.'   ) ; } ,[object Object],[object Object],[object Object],[object Object]
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.'   ) ; } ,[object Object],[object Object]
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 ; } ,[object Object],[object Object]
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  ) ; ,[object Object],[object Object],[object Object],[object Object]
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  ) ; ,[object Object],[object Object]
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 () ; }) ; ,[object Object],[object Object],[object Object]
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 ; }) ; ,[object Object],[object Object],[object Object]
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 ; ,[object Object],[object Object],[object Object]
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 ; ,[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
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 } } ,[object Object],[object Object],[object Object]
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 ) ; } ,[object Object],[object Object],[object Object],[object Object]
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 ; }) ; } ,[object Object],[object Object]
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

Más contenido relacionado

La actualidad más candente

jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksAddy Osmani
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyDavid Padbury
 
HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs SilverlightMatt Casto
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Libraryjeresig
 
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...
Finally, Professional Frontend Dev with ReactJS, WebPack & Symfony (Symfony C...Ryan Weaver
 
Create responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSCreate responsive websites with Django, REST and AngularJS
Create responsive websites with Django, REST and AngularJSHannes Hapke
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress DevelopmentAdam Tomat
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2fishwarter
 
Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Design patterns revisited with PHP 5.3
Design patterns revisited with PHP 5.3Fabien Potencier
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax ApplicationsSiarhei Barysiuk
 
What you need to know bout html5
What you need to know bout html5What you need to know bout html5
What you need to know bout html5Kevin DeRudder
 
Performance, Games, and Distributed Testing in JavaScript
Performance, Games, and Distributed Testing in JavaScriptPerformance, Games, and Distributed Testing in JavaScript
Performance, Games, and Distributed Testing in JavaScriptjeresig
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010Nicholas Zakas
 
HTML5 JavaScript APIs
HTML5 JavaScript APIsHTML5 JavaScript APIs
HTML5 JavaScript APIsRemy Sharp
 

La actualidad más candente (20)

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

Destacado

Nate Reist WCGR WP AJAX presentation
Nate Reist WCGR WP AJAX presentationNate Reist WCGR WP AJAX presentation
Nate Reist WCGR WP AJAX presentationnatereist
 
Tutorial beacon full_200815
Tutorial beacon full_200815Tutorial beacon full_200815
Tutorial beacon full_200815Makeitapp
 
[Ronald p. morash] bridge to abstract mathematics
[Ronald p. morash] bridge to abstract mathematics[Ronald p. morash] bridge to abstract mathematics
[Ronald p. morash] bridge to abstract mathematicsASRI ROMADLONI
 
Image processing (Signal Processing)
Image processing (Signal Processing)Image processing (Signal Processing)
Image processing (Signal Processing)Muhammad Waqas
 
MedSpring: the Nexus Water-Energy-Food (W-E-F) to strengthen the EU-Mediterr...
MedSpring:  the Nexus Water-Energy-Food (W-E-F) to strengthen the EU-Mediterr...MedSpring:  the Nexus Water-Energy-Food (W-E-F) to strengthen the EU-Mediterr...
MedSpring: the Nexus Water-Energy-Food (W-E-F) to strengthen the EU-Mediterr...UNIMED - Mediterranean Universities Union
 
Agricultural Productivity and Economic Development in Southern Africa
Agricultural Productivity and Economic Development in Southern AfricaAgricultural Productivity and Economic Development in Southern Africa
Agricultural Productivity and Economic Development in Southern AfricaJason Welker
 
Drupal - A Web Based Content Management System
Drupal - A Web Based Content Management SystemDrupal - A Web Based Content Management System
Drupal - A Web Based Content Management SystemSudarshan Bengani
 
Irrigation suitability in Malawi
Irrigation suitability in MalawiIrrigation suitability in Malawi
Irrigation suitability in MalawiMeyer_IFPRI
 
Selecting a content management system
Selecting a content management systemSelecting a content management system
Selecting a content management systemgmcinnis
 
Solving Equations
Solving EquationsSolving Equations
Solving Equationsswartzje
 
Early warning systems for food water-energy nexus in GMS region
Early warning systems for food water-energy nexus in GMS regionEarly warning systems for food water-energy nexus in GMS region
Early warning systems for food water-energy nexus in GMS regionPrabhakar SVRK
 
Behavioral Economics and the Design of Agricultural Index Insurance in Develo...
Behavioral Economics and the Design of Agricultural Index Insurance in Develo...Behavioral Economics and the Design of Agricultural Index Insurance in Develo...
Behavioral Economics and the Design of Agricultural Index Insurance in Develo...BASIS AMA Innovation Lab
 

Destacado (20)

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

Similar a WordPress and Ajax

JavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressJavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressIgor Benić
 
WordPress as a Content Management System
WordPress as a Content Management SystemWordPress as a Content Management System
WordPress as a Content Management SystemValent Mustamin
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkDirk Haun
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stackPaul Bearne
 
WordPress development paradigms, idiosyncrasies and other big words
WordPress development paradigms, idiosyncrasies and other big wordsWordPress development paradigms, idiosyncrasies and other big words
WordPress development paradigms, idiosyncrasies and other big wordsTomAuger
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 
Introduction to Plugin Programming, WordCamp Miami 2011
Introduction to Plugin Programming, WordCamp Miami 2011Introduction to Plugin Programming, WordCamp Miami 2011
Introduction to Plugin Programming, WordCamp Miami 2011David Carr
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)arcware
 
Google在Web前端方面的经验
Google在Web前端方面的经验Google在Web前端方面的经验
Google在Web前端方面的经验yiditushe
 
SXSW: Even Faster Web Sites
SXSW: Even Faster Web SitesSXSW: Even Faster Web Sites
SXSW: Even Faster Web SitesSteve Souders
 
Widgets: Making Your Site Great and Letting Others Help - WordCamp Victoria
Widgets: Making Your Site Great and Letting Others Help - WordCamp VictoriaWidgets: Making Your Site Great and Letting Others Help - WordCamp Victoria
Widgets: Making Your Site Great and Letting Others Help - WordCamp VictoriaJeff Richards
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Paul Bearne
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
WordPress as the Backbone(.js)
WordPress as the Backbone(.js)WordPress as the Backbone(.js)
WordPress as the Backbone(.js)Beau Lebens
 
How Not to Build a WordPress Plugin
How Not to Build a WordPress PluginHow Not to Build a WordPress Plugin
How Not to Build a WordPress PluginWill Norris
 

Similar a WordPress and Ajax (20)

JavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressJavaScript & AJAX in WordPress
JavaScript & AJAX in WordPress
 
WordPress as a Content Management System
WordPress as a Content Management SystemWordPress as a Content Management System
WordPress as a Content Management System
 
Using Geeklog as a Web Application Framework
Using Geeklog as a Web Application FrameworkUsing Geeklog as a Web Application Framework
Using Geeklog as a Web Application Framework
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
 
WordPress development paradigms, idiosyncrasies and other big words
WordPress development paradigms, idiosyncrasies and other big wordsWordPress development paradigms, idiosyncrasies and other big words
WordPress development paradigms, idiosyncrasies and other big words
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
WCLA12 JavaScript
WCLA12 JavaScriptWCLA12 JavaScript
WCLA12 JavaScript
 
Introduction to Plugin Programming, WordCamp Miami 2011
Introduction to Plugin Programming, WordCamp Miami 2011Introduction to Plugin Programming, WordCamp Miami 2011
Introduction to Plugin Programming, WordCamp Miami 2011
 
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
10 Things Every Plugin Developer Should Know (WordCamp Atlanta 2013)
 
Google在Web前端方面的经验
Google在Web前端方面的经验Google在Web前端方面的经验
Google在Web前端方面的经验
 
Sxsw 20090314
Sxsw 20090314Sxsw 20090314
Sxsw 20090314
 
SXSW: Even Faster Web Sites
SXSW: Even Faster Web SitesSXSW: Even Faster Web Sites
SXSW: Even Faster Web Sites
 
Widgets: Making Your Site Great and Letting Others Help - WordCamp Victoria
Widgets: Making Your Site Great and Letting Others Help - WordCamp VictoriaWidgets: Making Your Site Great and Letting Others Help - WordCamp Victoria
Widgets: Making Your Site Great and Letting Others Help - WordCamp Victoria
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
WordPress as the Backbone(.js)
WordPress as the Backbone(.js)WordPress as the Backbone(.js)
WordPress as the Backbone(.js)
 
How Not to Build a WordPress Plugin
How Not to Build a WordPress PluginHow Not to Build a WordPress Plugin
How Not to Build a WordPress Plugin
 
Php frameworks
Php frameworksPhp frameworks
Php frameworks
 
Fast by Default
Fast by DefaultFast by Default
Fast by Default
 
symfony & jQuery (phpDay)
symfony & jQuery (phpDay)symfony & jQuery (phpDay)
symfony & jQuery (phpDay)
 

Más de Ronald Huereca

Introduction to React for jQuery Developers
Introduction to React for jQuery DevelopersIntroduction to React for jQuery Developers
Introduction to React for jQuery DevelopersRonald Huereca
 
How to Successfully Take Over a WordPress Plugin
How to Successfully Take Over a WordPress PluginHow to Successfully Take Over a WordPress Plugin
How to Successfully Take Over a WordPress PluginRonald Huereca
 
Designing Plugins for Release
Designing Plugins for ReleaseDesigning Plugins for Release
Designing Plugins for ReleaseRonald Huereca
 
WordPress Must-Use Plugins (Quick Overview)
WordPress Must-Use Plugins (Quick Overview)WordPress Must-Use Plugins (Quick Overview)
WordPress Must-Use Plugins (Quick Overview)Ronald Huereca
 
WordPress Multisite General Overview
WordPress Multisite General OverviewWordPress Multisite General Overview
WordPress Multisite General OverviewRonald Huereca
 
WordPress Plugin Localization
WordPress Plugin LocalizationWordPress Plugin Localization
WordPress Plugin LocalizationRonald Huereca
 

Más de Ronald Huereca (6)

Introduction to React for jQuery Developers
Introduction to React for jQuery DevelopersIntroduction to React for jQuery Developers
Introduction to React for jQuery Developers
 
How to Successfully Take Over a WordPress Plugin
How to Successfully Take Over a WordPress PluginHow to Successfully Take Over a WordPress Plugin
How to Successfully Take Over a WordPress Plugin
 
Designing Plugins for Release
Designing Plugins for ReleaseDesigning Plugins for Release
Designing Plugins for Release
 
WordPress Must-Use Plugins (Quick Overview)
WordPress Must-Use Plugins (Quick Overview)WordPress Must-Use Plugins (Quick Overview)
WordPress Must-Use Plugins (Quick Overview)
 
WordPress Multisite General Overview
WordPress Multisite General OverviewWordPress Multisite General Overview
WordPress Multisite General Overview
 
WordPress Plugin Localization
WordPress Plugin LocalizationWordPress Plugin Localization
WordPress Plugin Localization
 

Último

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 

Último (20)

Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 

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.
  • 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.
  • 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 ( &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.
  • 30.
  • 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.
  • 33.
  • 34. Ajax Registration Form » Main Class » Shortcode Creation Adding the shortcode to a post
  • 35.
  • 36.
  • 37.
  • 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 () { $ ( &quot;#ajax-registration-form&quot; ) . 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 ( &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