WordPress and Ajax
-
Upload
ronald-huereca -
Category
Technology
-
view
116 -
download
0
description
Transcript of WordPress and Ajax
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 imPortant 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 scriptsrc - Location of the scriptdeps - 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
<?phpadd_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
<?phpadd_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
<?phpadd_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: "http://localhost:8888/ronalfy/wp-admin/admin-ajax.php",Location: "post",Manual: "false"
};/* ]]> */ </script><script type='text/javascript' src='http://localhost:8888/ronalfy/wp-content/plugins/wp-grins-lite/js/wp-grins.js?ver=1'></script>
The resulting HTML source:
jQuery(document).ready(function() {alert(wpgrins.Ajax_Url);
});
Localization used in JavaScript
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 stylesrc - Location of the styledeps - 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<?phpadd_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)
<?phpadd_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
<?phpadd_action('admin_menu', 'my_admin_menu');//Function to initialize the admin menufunction my_admin_menu() {
$page_hook = add_menu_page( "My Plugin Name Options", "My Plugin", 'administrator', 'my_plugin', 'my_plugin_admin_settings');
add_action("admin_print_scripts-$page_hook", 'my_plugin_load_scripts');}//Build the admin menu interfacefunction my_plugin_admin_settings() {
echo "My Plugin Page";}//Load our scriptsfunction 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
<?phpadd_action('wp_ajax_getcomment', 'callback_function');add_action('wp_ajax_nopriv_getcomment', 'callback_function'); function callback_function() {
//process data and send Ajax responseexit;
}?>
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
<?phpadd_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="getcomment_0">
<getcomments id="0" position="1"><response_data><![CDATA[]]></response_data><supplemental>
<awaiting_moderation><![CDATA[0]]></awaiting_moderation><approved><![CDATA[2,818]]></approved><spam><![CDATA[636]]></spam><trashed><![CDATA[0]]></trashed>
</supplemental></getcomments>
</response></wp_ajax>
The WP_Ajax_Response class sends back an XML document for use in JavaScript
WordPress and Ajax Foundation » WP_Ajax_Response » JavaScript Use
JavaScript object: wpAjax Uses a script handler of wp-ajax-response
wp_enqueue_script('my_script', get_stylesheet_directory_uri() .'/my_script.js', array("jquery", "wp-ajax-response") , "2.3");
The wpAjax JavaScript class is useful for parsing the Ajax response
The wp-ajax-response dependency
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<?phpclass Ajax_Registration {
//Constructorsfunction Ajax_Registration() { $this->__construct();}function __construct() {
//actions and shortcode}//Add the registration script to a pagefunction add_scripts() {}//Add Styles for the formfunction add_styles() {}function ajax_process_registration() {} //end ajax_process_registration//Perform shortcode page detectionfunction has_shortcode() {}//Add/save shortcode informationfunction post_save( $post_id ) {} //end post_save//Print out the shortcodefunction 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 = "<form id='ajax-registration-form'>";$return .= wp_nonce_field( 'submit_ajax-registration', '_registration_nonce', true, false );$return .= "<ul id='ajax-registration-list'>"; $return .= "<li><label for='firstname'>First name: </label><input type='text' size='30' name='firstname'
id='firstname' /></li>";$return .= "<li><label for='lastname'>Last name: </label><input type='text' size='30' name='lastname'
id='lastname' /></li>";$return .= "<li><label for='username'>Desired Username: </label><input type='text' size='30' name='username'
id='username' /></li>";$return .= "<li><label for='email'>E-mail Address: </label><input type='text' size='30' name='email'
id='email' /></li>";$return .= "<li><input type='submit' value='Submit Registration' name='ajax-submit'
id='ajax-submit' /></li>";$return .= "<li id='registration-status-message'></li>";$return .= "</ul>";$return .= "</form>";
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 contentpreg_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 notfunction 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 pagefunction 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 noncecheck_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 validationrequire_once( ABSPATH . WPINC . '/registration.php'); //Get post dataif ( !isset( $_POST['ajax_form_data'] ) ) die("-1");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 fieldsif ( 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 responseif ( 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 validationif ( !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 responseif ( 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() { $("#ajax-registration-form").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
$("#ajax-registration-form").submit(function() {//Clear all form errors$('#ajax-registration-form input').removeClass('error');//Update status message$("#registration-status-message").removeClass('error').addClass('success').html('Sending...');//Disable submit button$('#ajax-submit').attr("disabled", "disabled");
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("disabled", "disabled");//Serialize form datavar 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 Requestform_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 Responsefunction(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("disabled");var html = '';$.each(res.responses, function() {
$.each(this.errors, function() {$("#" + this.code).addClass('error');html = html + this.message + '<br />';
});});$("#registration-status-message").removeClass('success').addClass('error').html(html);
}
- 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() {
$("#registration-status-message").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("disabled");var html = '';$.each(res.responses, function() {
$.each(this.errors, function() {$("#" + this.code).addClass('error');html = html + this.message + '<br />';
});});$("#registration-status-message").removeClass('success').addClass('error').html(html);
} else {//no errors$.each(res.responses, function() {
$("#registration-status-message").addClass('success').html(this.data);return;
});}
}
Eat your heart out.
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