SlideShare a Scribd company logo
WORDPRESS & AJAX Presented by Ronald Huereca at WordCamp Philly 2010 Presentation online at:  http://www.wpajax.com/code
Who Am I? - Author of the WordPress and Ajax e-book http://www.wpajax.com - Plugin author of Ajax Edit Comments http://www.ajaxeditcomments.com - WordPress developer at WebDevStudios http://www.webdevstudios.com And third most im P ortant person in WordPress (important with a capital  P , dangit)
What is Ajax?
What is Ajax ? » What the heck does that mean? When you click on a rating, an event occurs The event and data is parsed and an Ajax request is sent The server processes the request, sends back a response, And the output is shown to the user

Recommended for you

HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs Silverlight

The document compares various features of HTML5 and Silverlight, including platforms supported, storage options, databases, offline capabilities, threading models, communication APIs, notifications, audio/video support, canvas drawing, and other miscellaneous features. Key differences discussed include HTML5's broader platform support versus Silverlight's reliance on the .NET framework and browser plugins. The document provides overviews and comparisons to help understand how the technologies compare in various areas.

silverlighthtml5
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library

This is the Google Tech Talk that I gave August 17th, 2007 on building a JavaScript library. I derived much of the talk from my experiences in building the jQuery and FUEL JavaScript libraries.

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...

If you're like me, you know that being a great backend developer isn't enough. To make *truly* great applications, we need to spend significant time in an area that's moving at a lightning pace: frontend development. This talk is for you: the backend developer that wants to hook their API's up to rich, interactive JavaScript frontends. To do that, first, we need to demystify a lot of new terms, like ES6/ES2015, ECMAScript, JSX, Babel and the idea that modern JavaScript (surprise) *requires* a build step. With this in mind, I'll give you a brief introduction into Webpack & the modular development it finally allows. But the real star is ReactJS. In the frontend world, you never know what new tech will *win*, but React is a star. I'll give you enough of an intro to get you rolling on your project. The new frontend dev world is huge! Consider the starting line down an exciting new journey.

babelreactjswebpack
WordPress and Ajax Foundation » What is needed? Load scripts and styles properly Use JavaScript Localization (to capture dynamic PHP content) Use Page Detection Know the WP Ajax actions and classes
WordPress and Ajax Foundation » Loading Scripts » wp_enqueue_script WordPress function:  wp_enqueue_script prevents duplicate scripts and allows for a predictable loading order via dependencies <?php wp_enqueue_script ( 'handle', 'src', 'deps', 'ver', 'in_footer' );  ?> handle  - Unique name for the script src  - Location of the script deps  - Array of dependencies (uses handler names) ver  - Version of the script (string) in_footer  - Load the scripts in the footer (boolean, default is false) wp_enqueue_script ( 'my_script', plugins_url (  'my_plugin/my_script.js’  ),  array ( 'jquery', 'another_script' ),  '1.0.0',  true );
WordPress and Ajax Foundation » Loading Scripts » wp_print_scripts WordPress action:  wp_print_scripts allows you to print scripts for the front-end and admin area <?php add_action (   'wp_print_scripts'  ,  'add_scripts'   ) ; function  add_scripts ()   { if   (  is_admin ()   )   return ; wp_enqueue_script (   'jquery ' ) ; } ?> Function name  needs to be unique Loads jQuery on every front-end page
WordPress and Ajax Foundation » Loading Scripts » admin_print_scripts WordPress action:  admin_print_scripts allows you to print scripts for admin area <?php add_action (   'admin_print_scripts'  ,  'add_admin_scripts'   ) ; function  add_admin_scripts ()   { wp_enqueue_script (   'jquery ' ) ; } ?> Function name  needs to be unique Loads jQuery on every admin page

Recommended for you

HTML 5 - Overview
HTML 5 - OverviewHTML 5 - Overview
HTML 5 - Overview

HTML 5 is the latest version of the HTML standard. It includes several new elements and features to improve structure and behavior. Some key changes include new semantic elements like <article>, <aside>, <header>, and <footer>; built-in support for audio and video; the <canvas> element for drawing graphics; and forms with new input types. HTML 5 aims to simplify HTML and separate structure and presentation, making code cleaner and pages more accessible. It is developed jointly by the WHATWG and W3C organizations.

phppaideguaphphtml5
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

The document discusses 10 steps to make a Django site more responsive by adding a REST API and using AngularJS for the front-end: 1) Create an API endpoint for the Django models, 2) Set up the JavaScript environment and install AngularJS, 3) Create a static AngularJS site, 4) Use verbatim tags to avoid conflicts between Django and AngularJS variables, 5) Connect AngularJS to the API, 6) Take advantage of the Django REST Framework features, 7) Handle asynchronous data loading, 8) Add forms and POST requests, 9) Clean up settings.py, and 10) Document the API. The goal is to keep the back-end lightweight Django while building a more responsive and

restdjangoangularjs
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development

Slide links: - https://lumberjack.rareloop.com - https://docs.lumberjack.rareloop.com - https://github.com/Rareloop/lumberjack-bedrock-installer - https://github.com/Rareloop/lumberjack - https://github.com/Rareloop/lumberjack-validation - https://github.com/Rareloop/hatchet - https://lizkeogh.com/2017/08/31/reflecting-reality/amp - https://www.upstatement.com/timber - https://roots.io/bedrock - https://scotch.io/bar-talk/s-o-l-i-d-the-first-five-principles-of-object-oriented-design - https://github.com/zendframework/zend-diactoros - https://www.php-fig.org - http://php-di.org --- Often WordPress themes are not easy to change, maintain or fun to work on. This can rule WordPress out as a viable option for bespoke, non-trivial websites. In this talk we’ll dive into how this happens & look at how we can benefit from software engineering techniques to help make your code easier to change. I’ll also show how using Lumberjack, a powerful MVC framework built on Timber, can be used to power-up your themes.

developmentlumberjackphp
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' ) ;

Recommended for you

Writing Pluggable Software
Writing Pluggable SoftwareWriting Pluggable Software
Writing Pluggable Software

"How to write pluggable software" presented by Tatsuhiko Miyagawa at YAPC::Asia 2007 in Tokyo on April 5th 2007.

The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2

The document discusses the Django web application framework. It describes Django as a high-level Python framework that encourages rapid development and clean design. It outlines Django's architecture, which follows an MVT pattern with models, views, templates, and a URL dispatcher. It also discusses Django's modules, like forms, administration, caching, and signals. An example project is provided to demonstrate starting a project, adding an app with a model, and exploring the admin interface.

djangopython
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

The document discusses how PHP 5.3 changes the implementation of common design patterns like the Singleton pattern and Observer pattern through the use of anonymous functions. It provides code examples of implementing these patterns in PHP 4/5.0-5.2 versus PHP 5.3 using features like closures, late static binding, and __invoke(). The document also proposes building a dependency injection container in PHP 5.3 using anonymous functions to describe object creation without instantiating objects. This approach results in a simple yet fully-featured dependency injector implementation in around 40 lines of code.

phpobserverdependency injection
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

Recommended for you

High-Quality JavaScript
High-Quality JavaScriptHigh-Quality JavaScript
High-Quality JavaScript

The document discusses best practices for developing high quality JavaScript applications. It recommends leveraging build tools like Grunt and integrating tools for linting, testing, minification and concatenation. Continuous integration with Jenkins is also suggested, as well as using IDEs and editors that support JavaScript. Architectural patterns like modules and design principles are important.

javascript clean code craftsmanship
End-to-end testing with geb
End-to-end testing with gebEnd-to-end testing with geb
End-to-end testing with geb

Why and when you need end-to-end tests, a spooky story with a 15 years software beast, and how to develop concise, maintainable functional tests using Groovy, Spock and Geb.

groovyspockgeb
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications

Day 6 of 7-days "JavaScript and Rich User Interfaces" training for my colleagues. It covers ways how to speed up your application.

yahooperformancejs
WordPress and Ajax Foundation » Page Detection » Front-end Example:  Loading Scripts Only When There are Comments <?php add_action ( 'wp_print_scripts' ,  'my_plugin_load_scripts' ) ; function  my_plugin_load_scripts ()   { global  $post; if   (   ! (  is_single ()   ||  is_page ()   )   ||   !is_object ( $post )   ||   $post -> comment_count == 0  )   return ; wp_enqueue_script ( 'jquery' ) ; } ?> Makes sure we’re on a post or a page Checks for the existence of the $post object (needed to get the comment count) Checks that there are comments on a post or page
WordPress and Ajax Foundation » Page Detection » Admin Area WordPress actions:  admin_print_scripts  and  admin_print_styles Page detection can be performed by adding the page name as a suffix for both actions - admin_print_scripts- suffix  (e.g., admin_print_scripts- post.php ) - admin_print_styles- suffix  (e.g., admin_print_styles- comment.php )
WordPress and Ajax Foundation » Page Detection » Admin Area Example: Adding a Script When Editing or Creating a Post uses post.php (when editing a post) and post-new.php (when creating a post) <?php add_action ( 'admin_print_scripts-post.php' ,  'my_plugin_load_scripts' ) ; add_action ( 'admin_print_scripts-post-new.php' ,  'my_plugin_load_scripts' ) ; function  my_plugin_load_scripts ()   { if   ( get_post_type ()  ==  'post' ) wp_enqueue_script ( 'jquery' ) ; } ?> Please note that  admin_print_scripts  and  admin_print_styles  use the same suffix format.
WordPress and Ajax Foundation » Page Detection » Admin Area Example: Page Detection for a Settings Page <?php add_action ( 'admin_menu' ,  'my_admin_menu' ) ; //Function to initialize the admin menu function  my_admin_menu ()   { $page_hook = add_menu_page (   &quot;My Plugin Name Options&quot; ,  &quot;My Plugin&quot; ,  'administrator' ,  'my_plugin' ,  'my_plugin_admin_settings' ) ; add_action ( &quot;admin_print_scripts-$page_hook&quot; ,  'my_plugin_load_scripts' ) ; } //Build the admin menu interface function  my_plugin_admin_settings ()   { echo   &quot;My Plugin Page&quot; ; } //Load our scripts function  my_plugin_load_scripts ()   { wp_enqueue_script ( 'jquery' ) ; } ?> When you add a menu page, the function returns a  page hook  you can use as a suffix for  admin_print_scripts  and  admin_print_styles More menu hooks are available here:  http://codex.wordpress.org/Adding_Administration_Menus

Recommended for you

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

The document provides an overview of HTML5 including: - New tags such as article, aside, audio, canvas, and video - The structure of an HTML5 page including the doctype, meta charset, and link types - Forms with new input types and validation attributes - Playing audio and video with HTML5 tags and controlling them with JavaScript - Drawing graphics on a canvas using JavaScript - Web workers for running scripts in background threads - Options for data storage including web storage, web SQL, and IndexedDB

html5kevinjavascript
SocketStream
SocketStreamSocketStream
SocketStream

A talk given at Node.js Cambridge about SocketStream, a realtime framework for single page apps. https://socketstream.com

node.jsrealtimesocketstream
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

This document discusses various techniques for measuring and optimizing JavaScript performance, including profiling tools in browsers like Firebug and Safari. It also addresses challenges in building multiplayer JavaScript games, such as latency issues, and proposes solutions like combining elements of strategy, intelligence and accuracy. The document concludes by covering distributed and automated testing techniques like TestSwarm that can help address challenges of testing JavaScript across many browsers and platforms.

jsconfjsconf09javascript
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

Recommended for you

High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010

This document summarizes Nicholas C. Zakas' presentation on high performance JavaScript. It discusses how the browser UI thread handles both UI updates and JavaScript execution sequentially. Long running JavaScript can cause unresponsive UIs. Techniques to ensure responsive UIs include limiting JavaScript execution time, using timers or web workers to break up processing, reducing repaints and reflows, and grouping style changes. Hardware acceleration and optimizing JavaScript engines have improved performance but responsive UIs still require discipline.

wdusajavascriptperformance
HTML5 JavaScript APIs
HTML5 JavaScript APIsHTML5 JavaScript APIs
HTML5 JavaScript APIs

HTML5 is all the rage with the cool kids, and although there's a lot of focus on the new language, there's lots of interesting new JavaScript APIs both in the HTML5 spec and separated out. This presentation will take you through demos and code behind the new JavaScript APIs, and explore where these features can be used

html5 jsconf jsconfeu
Nate Reist WCGR WP AJAX presentation
Nate Reist WCGR WP AJAX presentationNate Reist WCGR WP AJAX presentation
Nate Reist WCGR WP AJAX presentation

This document discusses using AJAX with JavaScript in WordPress. It defines AJAX as asynchronous JavaScript and XMLHttpRequests. The document outlines how to use AJAX in WordPress plugins and themes by hooking into wp_ajax_ and wp_ajax_nopriv_. It provides examples of common AJAX uses and walks through the steps of an AJAX transaction between JavaScript, the browser, and WordPress. Potential issues and tips are also covered.

wordpresswcgr wpgr
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

Recommended for you

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?

Jeremy Bird's presentation which was delivered at the 2014 Gerald Lacey Memorial Lecture at the Institution of Civil Engineers.

international water management institutejeremy birdiwmi
numerical analysis
numerical analysisnumerical analysis
numerical analysis

This document discusses sources of error in numerical calculations. It identifies two main types: round-off error, due to limitations in precision, and truncation error, due to approximations in numerical methods. Round-off error accumulates through repeated calculations and can dominate final results. Truncation error depends on how well the solution can be represented by the approximation. Care must be taken to evaluate errors and ensure results have enough significant figures to be meaningful for the problem.

Ajax Registration Form » Features Features we want A shortcode for inserting the form on a post or page Page detection for the shortcode No page re-loads (uses Ajax) Data validation is done via Ajax Error messages are shown via Ajax User is notified by e-mail when the registration has succeeded
Ajax Registration Form » Plugin File Structure Registration form will be written as a plugin ajax-registration.php (main plugin file) registration.js (our script file) registration.css (the plugin’s styles)
Ajax Registration Form » Class Structure Class structure for ajax-registration.php <?php class  Ajax_Registration  {   //Constructors function  Ajax_Registration ()   {   $this -> __construct () ; } function  __construct ()   { //actions and shortcode } //Add the registration script to a page function  add_scripts ()   { } //Add Styles for the form function  add_styles ()   { } function  ajax_process_registration ()   { }   //end ajax_process_registration //Perform shortcode page detection function  has_shortcode ()   { } //Add/save shortcode information function  post_save (  $post_id  )   { }   //end post_save //Print out the shortcode function  rform_shortcode (   )   { } }   //end class //Instantiate $ajaxregistration =  new  Ajax_Registration () ; ?>
Ajax Registration Form » Main Class » The Constructor  The class constructor will add all the actions and shortcode callbacks we need function  __construct ()   { //add scripts add_action (   'wp_print_scripts' ,  array (   & $this,  'add_scripts'   )   ) ; //add css add_action (   'wp_print_styles' ,  array (   & $this,  'add_styles'   )   ) ; //ajax add_action (   'wp_ajax_nopriv_submitajaxregistration' ,  array (   & $this,  'ajax_process_registration'   )   ) ; add_action (   'wp_ajax_submitajaxregistration' ,  array (   & $this,  'ajax_process_registration'   )   ) ; //when saving a post add_action (   'save_post' ,  array (   & $this,  'post_save'   )   ) ; //shortcode add_shortcode (   'rform' ,  array (   & $this,  'rform_shortcode'   )   ) ; } The  wp_print_scripts  and  wp_print_styles  actions are used for scripts and styles respectively The  wp_ajax  actions are used for a JavaScript action of  submitajaxregistration The  save_post  action will be used to assist us in page detection A shortcode of  rform  is created, with a callback method of  rform_shortcode

Recommended for you

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...

Water-Food-Energy Nexus in the context of groundwater use in India: Experience from three Indian States A presentation by Aditi Mukherji Presented at an ‘Expert Group Meeting on Improving Access to Water, Sanitation and Energy Services in Asia and the Pacific’ in Bangkok, Thailand on 20 March 2013

indiaiwminexus
[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

This document provides information about a mathematics textbook titled "Bridge to Abstract Mathematics: Mathematical Proof and Structures" by Ronald P. Morash. It is part of the Random House/Birkhauser Mathematics Series. The textbook is intended for sophomore to senior level university students and focuses on mathematical proof and reasoning. It covers topics like set theory, logic, relations, and number systems to prepare students for more advanced mathematics courses. The textbook emphasizes mathematical proofs and includes many examples and exercises for students to practice writing proofs. It is designed to be flexible and can be adapted to different course structures and student backgrounds.

Image processing (Signal Processing)
Image processing (Signal Processing)Image processing (Signal Processing)
Image processing (Signal Processing)

Introduction to image processing (or signal processing). Types of Image processing. Applications of Image processing. Applications of Digital image processing.

imagedipdigital image processing
Ajax Registration Form » Main Class » Shortcode Creation Class method:  rform_shortcode Returns the form data as a string function  rform_shortcode (   )   { $return =  &quot;<form id='ajax-registration-form'>&quot; ; $return  . = wp_nonce_field (   'submit_ajax-registration' ,  '_registration_nonce' ,  true ,  false   ) ; $return  . =  &quot;<ul id='ajax-registration-list'>&quot; ;  $return  . =  &quot;<li><label for='firstname'>First name: </label><input type='text' size='30' name='firstname'  id='firstname' /></li>&quot; ; $return  . =  &quot;<li><label for='lastname'>Last name: </label><input type='text' size='30' name='lastname'  id='lastname' /></li>&quot; ; $return  . =  &quot;<li><label for='username'>Desired Username: </label><input type='text' size='30' name='username'  id='username' /></li>&quot; ; $return  . =  &quot;<li><label for='email'>E-mail Address: </label><input type='text' size='30' name='email'  id='email' /></li>&quot; ; $return  . =  &quot;<li><input type='submit' value='Submit Registration' name='ajax-submit'  id='ajax-submit' /></li>&quot; ; $return  . =  &quot;<li id='registration-status-message'></li>&quot; ; $return  . =  &quot;</ul>&quot; ; $return  . =  &quot;</form>&quot; ;   return  $return; } Nonce action name of _registration_nonce (will be verified later) Form ID of ajax-registration-form (used in JavaScript) Input IDs and names of firstname, lastname, username, email (used in JavaScript) Status message ID of registration-status-message (used in JavaScript)
Ajax Registration Form » Main Class » Shortcode Creation Adding the shortcode to a post
Ajax Registration Form » Main Class » Page Detection Class method:  post_save Find out if the post has the rform shortcode, and set a custom field if so function  post_save (  $post_id  )   { //Retrieve the post object - If a revision, get the original post ID $revision = wp_is_post_revision (  $post_id  ) ; if   (  $revision  ) $post_id = $revision; $post = get_post (  $post_id  ) ;   //Perform a test for a shortcode in the post's content preg_match ( '/rform[^]*/is' , $post -> post_content, $matches ) ;      if   (   count (  $matches  )  == 0  )   { delete_post_meta (  $post_id,  '_ajax_registration'   ) ; }   else   { update_post_meta (  $post_id,  '_ajax_registration' ,  '1'   ) ; } }   //end post_save Retrieve the original post ID if a revision Test the post content for the shortcode  rform If the shortcode is present, set the  _ajax_registration  custom field.  If not, remove it.
Ajax Registration Form » Main Class » Page Detection Class method:  has_shortcode A conditional that lets us know if the post has the rform shortcode or not //Returns true if a post has the rform shortcode, false if not function  has_shortcode ()   { global  $post; if   (   !is_object ( $post )   )   return   false ;  if   (  get_post_meta (  $post -> ID,  '_ajax_registration' ,  true   )   )   return   true ; else return   false ; } Checks for a custom field of  _ajax_registration . If the custom field exists, return  true .  If not, return  false .

Recommended for you

Proof in Mathematics
Proof in MathematicsProof in Mathematics
Proof in Mathematics

The document provides instructions and content for a geometry course, including: - A checklist of tasks to complete like constructions, solving problems, and proving theorems 11-13. - Information on deductive reasoning and how it is used in mathematical proofs, establishing conclusions with certainty from given premises. - Definitions of key terms like theorem, converse, and corollary. - Examples of proofs, including Euclid's proof of the converse of Pythagoras' theorem and a proof that the square root of 2 is irrational.

CEU lecture 2 2016
CEU lecture 2 2016CEU lecture 2 2016
CEU lecture 2 2016

This document provides an overview of the development and evolution of the Common Agricultural Policy (CAP) of the European Union. It begins with the original objectives of the CAP as laid out in 1958, which focused on increasing productivity and farm incomes, market stabilization, and ensuring affordable food prices. However, the policy relied solely on price supports, which led to overproduction and high costs. Reforms in 1992 reduced price supports and introduced compensation payments, but these became entrenched over time. Further reforms decoupled payments from production but maintained historical payment amounts. The CAP remains costly but has shifted away from the most trade-distorting policies. Ongoing debates focus on policy coherence and the rationale for continuing direct payments.

common agricultural policyagricultural economics
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...

MedSpring: the Nexus Water-Energy-Food (W-E-F) to strengthen the EU-Mediterranean Cooperation on Research & Innovation Dr. PhD Gaetano Ladisa - CIHEAM - Istituto Agronomico Mediterraneo di Bari

watermedspringfood
Ajax Registration Form » Main Class » Add Scripts and Localization Class method:  add_scripts Add the registration script file and some JavaScript localization //Add the registration script to a page function  add_scripts ()   { if   (  is_admin ()   ||   ! $this -> has_shortcode ()   )   return ; wp_enqueue_script (   'ajax-registration-js' ,  plugins_url (   'js/registration.js'  , __FILE__   ) ,  array (   'jquery' ,  'wp-ajax-response'   ) ,  '1.0'   ) ; wp_localize_script (   'ajax-registration-js' ,  'ajaxregistration' ,  array (   'Ajax_Url'  = >  admin_url (   'admin-ajax.php'   )   )   ) ; } Uses conditionals  is_admin  and  has_shortcode  for page detection.  Will only load on the front-end where the shortcode exists in the page’s content. Localizes a JavaScript object of  ajaxregistration  with a variable called  Ajax_Url .  Ajax_Url  points to WordPress’  admin-ajax.php , which we’ll need to make our Ajax request in JavaScript.
Ajax Registration Form » Main Class » Add Styles Class method:  add_styles Add the registration CSS file function  add_styles ()   { if   (  is_admin ()   ||   ! $this -> has_shortcode ()   )   return ; wp_enqueue_style (   'ajax-registration-css' , plugins_url (   'css/registration.css'  , __FILE__   )   ) ; } Uses conditionals  is_admin  and  has_shortcode  for page detection.  Will only load on the front-end where the shortcode exists in the page’s content.
Ajax Registration Form » Main Class » The Ajax Processor Class method:  ajax_process_registration Processes the Ajax request and returns an Ajax response function  ajax_process_registration ()   { //Verify the nonce check_ajax_referer (   'submit_ajax-registration'   ) ;   exit ;   }   //end ajax_process_registration The first thing we do in the Ajax processor is check the passed nonce. The nonce is checked with  check_ajax_referer .  The nonce action named  submit_ajax-registration  was set in the  rform_shortcode  method.  The JavaScript file is responsible for setting a  $_POST  variable called  _ajax_nonce , which is what  check_ajax_referer  checks for.
Ajax Registration Form » Main Class » ajax_process_registration Parsing the data //Need registration.php for data validation require_once (  ABSPATH  .  WPINC  .   '/registration.php' ) ;   //Get post data if   (   !isset (   $_POST [ 'ajax_form_data' ]   )   )   die ( &quot;-1&quot; ) ; parse_str (   $_POST [ 'ajax_form_data' ] , $form_data  ) ; The WordPress file  registration.php  is included (includes such functions as  validate_username  and  username_exists ) Checks for  $_POST  variable  ajax_form_data  (the JavaScript file will set this variable) Parses the data into the  $form_data  array via  parse_str $form_data['firstname'] $form_data['lastname'] $form_data['email'] $form_data['username']

Recommended for you

CEU lecture 3 2016
CEU lecture 3 2016CEU lecture 3 2016
CEU lecture 3 2016

The document discusses issues related to international trade, including the theory of comparative advantage, limitations of trade models, barriers to trade such as tariffs and non-tariff barriers, and the impact of trade policies on developing countries. It notes that while free trade can expand global output, it also risks trapping countries in low-value production and limits opportunities for industrialization. Trade liberalization in agriculture has slowed due to policies in rich nations that affect world prices and new non-tariff barriers introduced.

tariffstradeagricultural economics
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

A presentation by Dr. Irene Forichi, former research officer for the Ministry of Agriculture, Zimbabwe, and Regional Emergency Agronomist for the Food and Agriculture Organization for Southern Africa. Dr. Forichi's spoke with our IB year 2 Economics classes about the role of agricultural productivity in contributing to human development and economic growth in Southern Africa.

ib economicseconomic developmentafrica
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

Drupal is a web-based content management system that stores text and other content in a database and dynamically retrieves it to present to users based on their requests. It can be used to build various websites including discussion sites, corporate sites, intranets, blogs, e-commerce sites, and directories. The document outlines Drupal's features for content management, user management, templating, blogging, multi-language and server support, administration, and scalability. It then provides a guide to installing Drupal with steps for downloading, configuring databases, modifying files, running the installation, and troubleshooting potential issues.

drupalsytemmanagement
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Sanitizing the entries Uses the sanitize_text_field function to sanitize the form inputs //Get the form fields $firstname = sanitize_text_field (  $form_data [ 'firstname' ]   ) ; $lastname = sanitize_text_field (  $form_data [ 'lastname' ]   ) ; $username = sanitize_text_field (  $form_data [ 'username' ]   ) ; $email = sanitize_text_field (  $form_data [ 'email' ]   ) ;   $error_response = $success_response =  new  WP_Ajax_Response () ; $errors =  new  WP_Error () ; Uses the sanitize_text_field WordPress function to sanitize the form inputs Instantiates an instance of WP_Ajax_Response (for sending the Ajax responses) Instantiates an instance of WP_Error (used as part of the Ajax response)
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Checking required entries We’ll use the WP_Error instance to add any errors if any fields are empty //Start data validation on firstname/lastname //Check required fields if   (   empty (  $firstname  )   )   $errors -> add (   'firstname' ,  'You must fill out a first name.' ,  'firstname'   ) ;   if   (   empty (  $lastname  )   )   $errors -> add (   'lastname' ,  'You must fill out a last name.'   ) ;   if   (   empty (  $username  )   )   $errors -> add (   'username' ,  'You must fill out a user name.'   ) ;   if   (   empty (  $email  )   )   $errors -> add (   'email' ,  'You must fill out an e-mail address.'   ) ; The first argument in  $errors->add  is an error code.  However, the code also doubles for the form  input  ID that will be used in JavaScript.
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: If any errors, send a response We’ll be using the WP_Ajax_Response instance to return a response if errors are present //If required fields aren't filled out, send response if   (   count   (  $errors -> get_error_codes ()   )   >  0  )   { $error_response -> add ( array ( 'what'  = >   'errors' , 'id'  = >  $errors )) ; $error_response -> send () ; exit ; } The  WP_Error   get_error_codes  method is used to determine if there are any errors saved If there are errors, we build the Ajax response using fields  what  and  id The  id  portion allows for a  WP_Error  object
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Check for a valid username //Add usernames we don't want used $invalid_usernames =  array (   'admin'   ) ; //Do username validation $username = sanitize_user (  $username  ) ; if   (   ! validate_username (  $username  )   ||   in_array (  $username, $invalid_usernames  )   )   { $errors -> add (   'username' ,  'Username is invalid.'   ) ; } if   (  username_exists (  $username  )   )   { $errors -> add (   'username' ,  'Username already exists.'   ) ; } Username is further sanitized via the  sanitize_user  WordPress function The  $invalid_usernames  array can contain usernames you don’t want users to select. If the username isn’t valid (via the  validate_username  function) or a username is reserved, we add an error - If the username already exists (via the  username_exists  function), we add an error

Recommended for you

Irrigation suitability in Malawi
Irrigation suitability in MalawiIrrigation suitability in Malawi
Irrigation suitability in Malawi

This document discusses irrigation suitability in Malawi. It finds that while there is potential for irrigation, current development is inadequate given climate risks and benefits. Suitability was assessed based on factors like topography, groundwater access, proximity to water and markets. While large areas are suitable, market access is the most restrictive constraint. Expanding irrigation requires improving access to markets, credit, and promoting agricultural water management technologies, especially targeting women and youth.

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

Presented by Claudia Ringler of IFPRI at the Global Water Systems Project: Water in the Anthropocene Conference May 21-24th in Bonn, Germany.

gwsp2013wle
Selecting a content management system
Selecting a content management systemSelecting a content management system
Selecting a content management system

• Understanding the ideal project lifecycle of a successful CMS implementation • How to create truly exceptional, results-driven Web experiences • Early considerations for building traffic through your website i.e. how to architect your website for maximum traffic, engagement and repeat visits and the feature sets you should look for in a CMS to make these happen • Strategies for bridging social technologies into your CMS for maximum visibility, audience engagement and business benefit • Current business and technology trends in Web Content Management • The most common Web CMS pitfalls, and Best Practices for avoiding them.

semsitecoreseo
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Check for a valid e-mail address //Do e-mail address validation if   (   ! is_email (  $email  )   )   { $errors -> add (   'email' ,  'E-mail address is invalid.'   ) ; } if   ( email_exists ( $email ))   { $errors -> add (   'email' ,  'E-mail address is already in use.'   ) ; } If the e-mail address is invalid (via the  is_email  function), we add an error If the e-mail address already exists (via the  email_exists  function), we add an error
Ajax Registration Form » Main Class » ajax_process_registration Data Validation: If any further errors, send a response We’ll be using the WP_Ajax_Response instance to return a response if errors are present //If required fields aren't filled out, send response if   (   count   (  $errors -> get_error_codes ()   )   >  0  )   { $error_response -> add ( array ( 'what'  = >   'errors' , 'id'  = >  $errors )) ; $error_response -> send () ; exit ; } We have to assume that all fields aren’t empty at this point Only invalid username/email errors will be sent
Ajax Registration Form » Main Class » ajax_process_registration Create the User Object All data has been validated.  Create the User object. //Everything has been validated, proceed with creating the user //Create the user $user_pass = wp_generate_password () ; $user =  array ( 'user_login'  = >  $username, 'user_pass'  = >  $user_pass, 'first_name'  = >  $firstname, 'last_name'  = >  $lastname, 'user_email'  = >  $email ) ; $user_id = wp_insert_user (  $user  ) ; A user password is generated (via  wp_generate_password ) A  $user  array is created with fields  user_login ,  user_pass ,  first_name ,  last_name , and  user_email User is created by passing the  $user  array to function  wp_insert_user Function  wp_insert_user  returns the new user’s ID
Ajax Registration Form » Main Class » ajax_process_registration Send the Registration E-mail User has been created.  Send a registration e-mail. /*Send e-mail to admin and new user -  You could create your own e-mail instead of using this function*/ wp_new_user_notification (  $user_id, $user_pass  ) ; A user e-mail is sent by passing the variables  $user_id  and  $user_pass  to the  wp_new_user_notification  function You could skip this step and instead create a custom e-mail (using  wp_mail )

Recommended for you

Solving Equations
Solving EquationsSolving Equations
Solving Equations

This document provides an overview of equations in one variable, including: - Defining equations and expressions, and distinguishing between the two - Identifying linear equations and determining if a number is a solution - Explaining properties of equality like addition, subtraction, multiplication, and division - Outlining the steps to solve linear equations in one variable - Describing types of linear equations like conditional, identity, and contradiction

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

For a full paper on this subject, please refer to the links below: http://enviroscope.iges.or.jp/modules/envirolib/view.php?docid=3390 http://gis.gms-eoc.org/GMS2020_WS-MATERIALS/2.1.4%20Prabhakar_Climate_Risks_to_Agriculture.pdf

gms regionfood-water-energyearly warning systems
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...

UC Davis Professor Michael Carter presented, "Behavioral Economics and the Design of Agricultural Index Insurance in Developing Countries" at the 2014 International Agricultural Risk, Finance, and Insurance Conference (IARFIC).

basisindex insuranceagricultural development
Ajax Registration Form » Main Class » ajax_process_registration Sending the Ajax Response User has been created.  Let’s send back an Ajax response. //Send back a response $success_response -> add ( array ( 'what'  = >   'object' , 'data'  = >   'User registration successful.  Please check your e-mail.' )) ; $success_response -> send () ; exit ; }   //end ajax_process_registration The data field in the Ajax response is used for sending a string message back to JavaScript.  This message will be used in our form’s status area.
Ajax Registration Form » The CSS » registration.css Adding the CSS Code Code will go into the registration.css file #ajax-registration-list { list-style-type :  none ; } #ajax-registration-list label { display :  block ; } #ajax-registration-form .error { background-color :  #FFEBE8 ; border :  1px solid #CC0000 ; } #ajax-registration-form .success { background-color :  #FFFFE0 ; border :  1px solid #E6DB55 ; } Basic CSS is used here for the form layout and the error/status messages.
Ajax Registration Form » The JavaScript » registration.js JavaScript structure A jQuery namespace called registrationform is used jQuery ( document ) .ready ( function ()   { var  $  =  jQuery; $.registrationform  =   { init :  function ()   {     } } ;  //end .registrationform $.registrationform.init () ; }) ; - A jQuery object named  registrationform  is created Within the  registrationform  object, a there is a placeholder function named init The function is initialized by calling  $.registrationform.init
Ajax Registration Form » The JavaScript » registration.js JavaScript function: init - Capturing the submit event The form has an ID of ajax-registration-form, which we’ll use to capture the submit event init :  function ()   {   $ ( &quot;#ajax-registration-form&quot; ) . submit ( function ()   { return   false ; }) ; } The form ID ( ajax-registration-form ) is used with the jQuery  submit  event.

Recommended for you

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 ...

This document discusses using river basin modeling to analyze the water-food-energy nexus in Egypt. It describes how river basin models represent water systems as networks of nodes and links and can be used for simulation or optimization modeling. Examples of scenarios analyzed include adding hydropower, assessing climate change impacts, and changing water allocation rules. Modeling results are presented for Pakistan under different temperature increase and precipitation change scenarios, comparing historical and optimized allocation. River basin models are concluded to be useful for assessing impacts of changes in food, water, and energy policies and allocations across these sectors.

egyptegyptsspifpri
JavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressJavaScript & AJAX in WordPress
JavaScript & AJAX in WordPress

This document outlines a WordPress webinar about JavaScript and AJAX presented by Igor Benić, a WordPress developer and educator. The webinar will cover including JavaScript in WordPress, creating global JavaScript objects, how AJAX works in WordPress, and an example of front-end form submission. Attendees can learn more from Igor Benić through an online course on becoming a WordPress developer or by becoming a member of his website.

wordpressjavascriptajax
WordPress as a Content Management System
WordPress as a Content Management SystemWordPress as a Content Management System
WordPress as a Content Management System

WordPress as a Content Management System, by Setyagus Sucipto (http://twitter.com/agoes82), from iCreativeLabs Studio, Bandung for WORDCAMPID - WordCamp Indonesia 2010. Auditorium Gunadarma University, Depok, January 30, 2010

wordpresswordcampwordcampid
Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Clearing any error messages In the event the form has previously been submitted, we’ll need to clear all previous messages $ ( &quot;#ajax-registration-form&quot; ) . submit ( function ()   { //Clear all form errors $ ( '#ajax-registration-form input' ) .removeClass ( 'error' ) ; //Update status message $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'error' ) .addClass ( 'success' ) .html ( 'Sending...' ) ; //Disable submit button $ ( '#ajax-submit' ) .attr ( &quot;disabled&quot;,   &quot;disabled&quot; ) ;   return   false ; }) ; All form inputs are cleared of errors (by removing the  error  CSS class) The status message (with ID of  registration-status-message ) is updated with the  success  CSS class and given the text “Sending…” The  submit  button (with ID  ajax-submit ) is disabled so the user can’t click it again during the submission process
Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Parse the Form Data We’ll use jQuery to parse the form data into a string we can pass via Ajax //Disable submit button $ ( '#ajax-submit' ) .attr ( &quot;disabled&quot;,   &quot;disabled&quot; ) ; //Serialize form data var  form_data  =  $ ( '#ajax-registration-form input' ) .serializeArray () ; form_data  =  $.param ( form_data ) ;   return   false ; All form inputs are captured and serialized to an array via the  serializeArray  function The serialized form data is then converted to a url-encoded string via the  param  function. The form_data variable now has a value similar to:  _registration_nonce=0ca8be2b7b&firstname=Ronald&lastname=Huereca&username=ronalfy&email=ron%40ronalfy.com
Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Submit the Ajax Request form_data  =  $.param ( form_data ) ;   //Submit ajax request $.post (  ajaxregistration.Ajax_Url ,   {   action :   'submitajaxregistration',   ajax_form_data :  form_data ,   _ajax_nonce :  $ ( '#_registration_nonce' ) .val ()   } , function ( data ){ //Success code goes here } ) ; return   false ; The jQuery post function acts as an Ajax POST event We pass it the URL to WordPress’  admin-ajax.php  file (via localized JavaScript variable  ajaxregistration.Ajax_Url ) The Ajax action  submitajaxregistration  is used for the WordPress  wp_ajax  action A post variable named  ajax_form_data  contains all our form data A post variable named  _ajax_nonce  contains the form’s nonce Finally, a callback method is created to handle the Ajax response (the response will be held in the  data  variable)
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response function ( data ){ var  res  =  wpAjax.parseAjaxResponse ( data ,   'ajax-response' ) ; if   ( res.errors )   { //errors }   else   { //no errors } } Data is parsed via the  parseAjaxResponse  function If errors are detected, spit out errors If no errors are detected, display a success mesage

Recommended for you

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

Slides for the workshop "Using Geeklog as a Web Application Framework", as held at - LinuxTag 2006, Wiesbaden, Germany, 2006-05-06 - PHP user group meeting, Stuttgart, Germany, 2006-05-10 - FrOSCon, Bonn, Germany, 2006-06-24

frosconframeworkwebapp
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack

This document discusses using WordPress as a web application framework. It outlines reasons for and against using WordPress, including that it is stable, supported by a large community, and scales well, but also has some code debt and uses PHP. It then explains how to build applications with WordPress, including using actions and filters, developing a JSON API, integrating jQuery and Backbone, leveraging the template hierarchy, and using custom post types and metadata. It also provides examples of caching external API requests and using transients.

word
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

For seasoned developers approaching WordPress customization or development for the first time the biggest challenge is often not learning the API and method calls: it's grasping the idiosyncrasies of the WordPress framework. In this 45-minute presentation aimed at web coders who are interested in diving into WordPress customization and development, you will learn the key idioms that will accelerate your learning curve and help you approach the framework from a best practices perspective: template hierarchies, themes and child themes, taxonomies, filters and action hooks, execution order and other need-to-know concepts will be presented as well as tips on what the most active online developer communities are and the best places to go for quick (free) help and advice.

wordpresswordcampwordcamp montreal
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The parsed data (if errors are detected)
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The errors data
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The errors data Iterate through each response, and iterate through each error within the response if   ( res.errors )   { //form errors //re-enable submit button $ ( '#ajax-submit' ) .removeAttr ( &quot;disabled&quot; ) ; var  html  =   '' ; $.each ( res.responses ,  function ()   { $.each (this .errors ,  function ()   { $ ( &quot;#&quot;   +   this .code ) .addClass ( 'error' ) ; html  =  html  +   this .message  +   '<br />' ; }) ; }) ; $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'success' ) .addClass ( 'error' ) .html ( html ) ; } There could be multiple responses, so we iterate through each one Within each response are several errors, so we iterate through those and build an HTML string with all of the error messages Furthermore, since each error has a code that identifies the form  input , we add an  error  class (via CSS) to show that there is an error Finally, we update our status message with the errors
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Example Output If there are any errors, this is what you might see

Recommended for you

Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress

This document discusses JavaScript and how it is used on over 92% of websites. It covers JavaScript fundamentals like variable scope, hoisting, and the this keyword. It also discusses how JavaScript allows first-class functions and functional programming. The document then covers how to properly manage scripts in WordPress using functions like wp_register_script, wp_enqueue_script, and wp_localize_script to internationalize scripts. It concludes by mentioning additional JavaScript topics to explore like closures and functional programming.

WCLA12 JavaScript
WCLA12 JavaScriptWCLA12 JavaScript
WCLA12 JavaScript

Reviews the basis of using JavaScript within WordPress. How to load in scripts correctly and move PHP data into JavaScripts for later use. Presented at WordCamp LA 2012

wordpresswordcamplos angeles
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

An intro lecture on how to customize WordPress by writing your own plugins in PHP, whether for publication or just for your own projects.

wordpresspluginwordcamp
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Success If there are no errors, we parse the data in the success portion of the conditional }   else   { //no errors $.each ( res.responses ,  function ()   { $ ( &quot;#registration-status-message&quot; ) .addClass ( 'success' ) .html (this .data ) ; return ; }) ; } There could be multiple responses, so we iterate through each one Output the success message (via the this.data variable)
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Success Output If there aren’t any errors, this is what you might see
Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Full Function Code function ( data ){ var  res  =  wpAjax.parseAjaxResponse ( data ,   'ajax-response' ) ; if   ( res.errors )   { //form errors //re-enable submit button $ ( '#ajax-submit' ) .removeAttr ( &quot;disabled&quot; ) ; var  html  =   '' ; $.each ( res.responses ,  function ()   { $.each (this .errors ,  function ()   { $ ( &quot;#&quot;   +   this .code ) .addClass ( 'error' ) ; html  =  html  +   this .message  +   '<br />' ; }) ; }) ; $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'success' ) .addClass ( 'error' ) .html ( html ) ; }   else   { //no errors $.each ( res.responses ,  function ()   { $ ( &quot;#registration-status-message&quot; ) .addClass ( 'success' ) .html (this .data ) ; return ; }) ; } } Eat your heart out.
Conclusion » The Code Download link The sample Ajax registration form plugin can be found at:  http://www.wpajax.com/code

Recommended for you

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)

The document outlines 10 things that every WordPress plugin developer should know, including enabling debugging, prefixing functions, enqueuing scripts and styles properly, only including JS/CSS on admin pages, using AJAX in the admin, adding extensibility hooks, supporting multisite, internationalization, security, and using helpful functions and constants. It provides examples and explanations for each topic to help plugin developers write more effective and secure code.

wordpress wordcamp atlanta
SXSW: Even Faster Web Sites
SXSW: Even Faster Web SitesSXSW: Even Faster Web Sites
SXSW: Even Faster Web Sites

Presented at SXSW '09, this talk covers five best practices from my next book: Load scripts without blocking, Coupling asynchronous scripts, Don't scatter inline scripts, Use iframes sparingly, and Flush the document early.

Sxsw 20090314
Sxsw 20090314Sxsw 20090314
Sxsw 20090314

The document summarizes Steve Souders' presentation on optimizing frontend performance. It discusses the importance of frontend optimization, common techniques like minimizing HTTP requests and leveraging a CDN. It then covers strategies for loading scripts asynchronously without blocking parallel downloads or rendering, including techniques like script DOM element, XHR injection, and coupling asynchronous scripts with dependencies.

Conclusion » Want to Know More? What to know more?  Buy my damn book! http://www.wpajax.com
Conclusion » Want to Know More? What to know more?  Buy my damn book!  I mean, pretty please, buy my book. http://www.wpajax.com
Conclusion » WordPress and Ajax » The End - Twitter @ronalfy - Skype ronalfy - Personal site (rants and musings) http://www.ronalfy.com - WordPress and Ajax e-book http://www.wpajax.com That’s it!  Thank you for your time. - Ajax Edit Comments http://www.ajaxeditcomments.com - WebDevStudios http://www.webdevstudios.com

More Related Content

What's hot

jQuery UI and Plugins
jQuery UI and PluginsjQuery UI and Plugins
jQuery UI and Plugins
Marc Grabanski
 
jQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & TricksjQuery Proven Performance Tips & Tricks
jQuery Proven Performance Tips & Tricks
Addy Osmani
 
HTML5 for the Silverlight Guy
HTML5 for the Silverlight GuyHTML5 for the Silverlight Guy
HTML5 for the Silverlight Guy
David Padbury
 
HTML5 vs Silverlight
HTML5 vs SilverlightHTML5 vs Silverlight
HTML5 vs Silverlight
Matt Casto
 
Building a JavaScript Library
Building a JavaScript LibraryBuilding a JavaScript Library
Building a JavaScript Library
jeresig
 
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
 
HTML 5 - Overview
HTML 5 - OverviewHTML 5 - Overview
HTML 5 - Overview
Marcelio Leal
 
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
Hannes Hapke
 
[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development[Bristol WordPress] Supercharging WordPress Development
[Bristol WordPress] Supercharging WordPress Development
Adam Tomat
 
Writing Pluggable Software
Writing Pluggable SoftwareWriting Pluggable Software
Writing Pluggable Software
Tatsuhiko Miyagawa
 
The Django Web Application Framework 2
The Django Web Application Framework 2The Django Web Application Framework 2
The Django Web Application Framework 2
fishwarter
 
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
Fabien Potencier
 
High-Quality JavaScript
High-Quality JavaScriptHigh-Quality JavaScript
High-Quality JavaScript
Marc Bächinger
 
End-to-end testing with geb
End-to-end testing with gebEnd-to-end testing with geb
End-to-end testing with geb
Jesús L. Domínguez Muriel
 
High Performance Ajax Applications
High Performance Ajax ApplicationsHigh Performance Ajax Applications
High Performance Ajax Applications
Siarhei 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 html5
Kevin DeRudder
 
SocketStream
SocketStreamSocketStream
SocketStream
Paul Jensen
 
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
jeresig
 
High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010High Performance JavaScript - WebDirections USA 2010
High Performance JavaScript - WebDirections USA 2010
Nicholas Zakas
 
HTML5 JavaScript APIs
HTML5 JavaScript APIsHTML5 JavaScript APIs
HTML5 JavaScript APIs
Remy Sharp
 

What's hot (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
 

Viewers also liked

Nate Reist WCGR WP AJAX presentation
Nate Reist WCGR WP AJAX presentationNate Reist WCGR WP AJAX presentation
Nate Reist WCGR WP AJAX presentation
natereist
 
Tutorial beacon full_200815
Tutorial beacon full_200815Tutorial beacon full_200815
Tutorial beacon full_200815
Makeitapp
 
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?
International Water Management Institute (IWMI)
 
numerical analysis
numerical analysisnumerical analysis
numerical analysis
'Anand Kumar'
 
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...
International Water Management Institute (IWMI)
 
[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
ASRI ROMADLONI
 
Image processing (Signal Processing)
Image processing (Signal Processing)Image processing (Signal Processing)
Image processing (Signal Processing)
Muhammad Waqas
 
Proof in Mathematics
Proof in MathematicsProof in Mathematics
Proof in Mathematics
mscartersmaths
 
CEU lecture 2 2016
CEU lecture 2 2016CEU lecture 2 2016
CEU lecture 2 2016
Jorge Nunez Ferrer
 
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
 
CEU lecture 3 2016
CEU lecture 3 2016CEU lecture 3 2016
CEU lecture 3 2016
Jorge Nunez Ferrer
 
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
Jason 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 System
Sudarshan Bengani
 
Irrigation suitability in Malawi
Irrigation suitability in MalawiIrrigation suitability in Malawi
Irrigation suitability in Malawi
Meyer_IFPRI
 
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
International Water Management Institute (IWMI)
 
Selecting a content management system
Selecting a content management systemSelecting a content management system
Selecting a content management system
gmcinnis
 
Solving Equations
Solving EquationsSolving Equations
Solving Equations
swartzje
 
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
Prabhakar 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
 
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 ...
International Food Policy Research Institute (IFPRI)
 

Viewers also liked (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 to WordPress and Ajax

JavaScript & AJAX in WordPress
JavaScript & AJAX in WordPressJavaScript & AJAX in WordPress
JavaScript & AJAX in WordPress
Igor Benić
 
WordPress as a Content Management System
WordPress as a Content Management SystemWordPress as a Content Management System
WordPress as a Content Management System
Valent 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 Framework
Dirk Haun
 
Using WordPress as your application stack
Using WordPress as your application stackUsing WordPress as your application stack
Using WordPress as your application stack
Paul 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 words
TomAuger
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
WCLA12 JavaScript
WCLA12 JavaScriptWCLA12 JavaScript
WCLA12 JavaScript
Jeffrey Zinn
 
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
David 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
 
SXSW: Even Faster Web Sites
SXSW: Even Faster Web SitesSXSW: Even Faster Web Sites
SXSW: Even Faster Web Sites
Steve Souders
 
Sxsw 20090314
Sxsw 20090314Sxsw 20090314
Sxsw 20090314
guestcabcf63
 
Google在Web前端方面的经验
Google在Web前端方面的经验Google在Web前端方面的经验
Google在Web前端方面的经验
yiditushe
 
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
Jeff Richards
 
Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919Childthemes ottawa-word camp-1919
Childthemes ottawa-word camp-1919
Paul Bearne
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
Wildan 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 Plugin
Will Norris
 
Php frameworks
Php frameworksPhp frameworks
Php frameworks
Anil Kumar Panigrahi
 
Fast by Default
Fast by DefaultFast by Default
Fast by Default
Abhay Kumar
 
symfony & jQuery (phpDay)
symfony & jQuery (phpDay)symfony & jQuery (phpDay)
symfony & jQuery (phpDay)
Massimiliano Arione
 

Similar to 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)
 
SXSW: Even Faster Web Sites
SXSW: Even Faster Web SitesSXSW: Even Faster Web Sites
SXSW: Even Faster Web Sites
 
Sxsw 20090314
Sxsw 20090314Sxsw 20090314
Sxsw 20090314
 
Google在Web前端方面的经验
Google在Web前端方面的经验Google在Web前端方面的经验
Google在Web前端方面的经验
 
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)
 

More from Ronald Huereca

Introduction to React for jQuery Developers
Introduction to React for jQuery DevelopersIntroduction to React for jQuery Developers
Introduction to React for jQuery Developers
Ronald 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 Plugin
Ronald Huereca
 
Designing Plugins for Release
Designing Plugins for ReleaseDesigning Plugins for Release
Designing Plugins for Release
Ronald 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 Overview
Ronald Huereca
 
WordPress Plugin Localization
WordPress Plugin LocalizationWordPress Plugin Localization
WordPress Plugin Localization
Ronald Huereca
 

More from 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
 

Recently uploaded

Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
Pigging Solutions
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
jackson110191
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
BookNet Canada
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
Matthew Sinclair
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Bert Blevins
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
SynapseIndia
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
Emerging Tech
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Chris Swan
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
KAMAL CHOUDHARY
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
Aurora Consulting
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
BookNet Canada
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
Neo4j
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
Toru Tamaki
 
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
welrejdoall
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
RaminGhanbari2
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
Eric D. Schabell
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
Larry Smarr
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
Larry Smarr
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
huseindihon
 
Mitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing SystemsMitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing Systems
ScyllaDB
 

Recently uploaded (20)

Pigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdfPigging Solutions Sustainability brochure.pdf
Pigging Solutions Sustainability brochure.pdf
 
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdfINDIAN AIR FORCE FIGHTER PLANES LIST.pdf
INDIAN AIR FORCE FIGHTER PLANES LIST.pdf
 
Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...Transcript: Details of description part II: Describing images in practice - T...
Transcript: Details of description part II: Describing images in practice - T...
 
20240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 202420240705 QFM024 Irresponsible AI Reading List June 2024
20240705 QFM024 Irresponsible AI Reading List June 2024
 
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
Understanding Insider Security Threats: Types, Examples, Effects, and Mitigat...
 
How RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptxHow RPA Help in the Transportation and Logistics Industry.pptx
How RPA Help in the Transportation and Logistics Industry.pptx
 
Implementations of Fused Deposition Modeling in real world
Implementations of Fused Deposition Modeling  in real worldImplementations of Fused Deposition Modeling  in real world
Implementations of Fused Deposition Modeling in real world
 
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
Fluttercon 2024: Showing that you care about security - OpenSSF Scorecards fo...
 
Recent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS InfrastructureRecent Advancements in the NIST-JARVIS Infrastructure
Recent Advancements in the NIST-JARVIS Infrastructure
 
Quality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of TimeQuality Patents: Patents That Stand the Test of Time
Quality Patents: Patents That Stand the Test of Time
 
Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024Details of description part II: Describing images in practice - Tech Forum 2024
Details of description part II: Describing images in practice - Tech Forum 2024
 
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdfBT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
BT & Neo4j: Knowledge Graphs for Critical Enterprise Systems.pptx.pdf
 
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
論文紹介:A Systematic Survey of Prompt Engineering on Vision-Language Foundation ...
 
Manual | Product | Research Presentation
Manual | Product | Research PresentationManual | Product | Research Presentation
Manual | Product | Research Presentation
 
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyyActive Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
Active Inference is a veryyyyyyyyyyyyyyyyyyyyyyyy
 
Observability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetryObservability For You and Me with OpenTelemetry
Observability For You and Me with OpenTelemetry
 
The Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive ComputingThe Rise of Supernetwork Data Intensive Computing
The Rise of Supernetwork Data Intensive Computing
 
The Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU CampusesThe Increasing Use of the National Research Platform by the CSU Campuses
The Increasing Use of the National Research Platform by the CSU Campuses
 
find out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challengesfind out more about the role of autonomous vehicles in facing global challenges
find out more about the role of autonomous vehicles in facing global challenges
 
Mitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing SystemsMitigating the Impact of State Management in Cloud Stream Processing Systems
Mitigating the Impact of State Management in Cloud Stream Processing Systems
 

WordPress and Ajax

  • 1. WORDPRESS & AJAX Presented by Ronald Huereca at WordCamp Philly 2010 Presentation online at: http://www.wpajax.com/code
  • 2. Who Am I? - Author of the WordPress and Ajax e-book http://www.wpajax.com - Plugin author of Ajax Edit Comments http://www.ajaxeditcomments.com - WordPress developer at WebDevStudios http://www.webdevstudios.com And third most im P ortant person in WordPress (important with a capital P , dangit)
  • 4. What is Ajax ? » What the heck does that mean? When you click on a rating, an event occurs The event and data is parsed and an Ajax request is sent The server processes the request, sends back a response, And the output is shown to the user
  • 5. WordPress and Ajax Foundation » What is needed? Load scripts and styles properly Use JavaScript Localization (to capture dynamic PHP content) Use Page Detection Know the WP Ajax actions and classes
  • 6. WordPress and Ajax Foundation » Loading Scripts » wp_enqueue_script WordPress function: wp_enqueue_script prevents duplicate scripts and allows for a predictable loading order via dependencies <?php wp_enqueue_script ( 'handle', 'src', 'deps', 'ver', 'in_footer' ); ?> handle - Unique name for the script src - Location of the script deps - Array of dependencies (uses handler names) ver - Version of the script (string) in_footer - Load the scripts in the footer (boolean, default is false) wp_enqueue_script ( 'my_script', plugins_url ( 'my_plugin/my_script.js’ ), array ( 'jquery', 'another_script' ), '1.0.0', true );
  • 7. WordPress and Ajax Foundation » Loading Scripts » wp_print_scripts WordPress action: wp_print_scripts allows you to print scripts for the front-end and admin area <?php add_action ( 'wp_print_scripts' , 'add_scripts' ) ; function add_scripts () { if ( is_admin () ) return ; wp_enqueue_script ( 'jquery ' ) ; } ?> Function name needs to be unique Loads jQuery on every front-end page
  • 8. WordPress and Ajax Foundation » Loading Scripts » admin_print_scripts WordPress action: admin_print_scripts allows you to print scripts for admin area <?php add_action ( 'admin_print_scripts' , 'add_admin_scripts' ) ; function add_admin_scripts () { wp_enqueue_script ( 'jquery ' ) ; } ?> Function name needs to be unique Loads jQuery on every admin page
  • 9. WordPress and Ajax Foundation » Script Localization » wp_localize_script WordPress function: wp_localize_script allows you to capture dynamic PHP data for use in JavaScript wp_localize_script ( 'javascript_handle' , 'javascript_object_name' , 'l10n' ) ; Object name to be created in JavaScript Same handler name used for wp_enqueue_script An associative array of localized strings
  • 10. WordPress and Ajax Foundation » Script Localization » wp_localize_script WordPress function: wp_localize_script example <?php add_action ( 'wp_print_scripts' , 'add_scripts' ) ; function add_scripts (){ wp_enqueue_script ( 'wp_grins' , plugins_url ( 'wp-grins-lite/js/wp-grins.js' ) , array ( 'jquery' ) , 1 . 0 ) ;   $localized_variables = array ( 'Ajax_Url' = > admin_url ( 'admin-ajax.php' ) , 'Location' = > 'post' , 'Manual' = > 'false' ) ; wp_localize_script ( 'wp_grins' , 'wpgrins' , $localized_variables ) ; } ?> Object name to be created in JavaScript Localized variables An associative array of localized strings
  • 11. WordPress and Ajax Foundation » Script Localization » wp_localize_script WordPress function: wp_localize_script allows you to capture dynamic PHP data for use in JavaScript <script type= 'text/javascript' >   /* <![CDATA[ */ var wpgrins = { Ajax_Url : &quot;http://localhost:8888/ronalfy/wp-admin/admin-ajax.php&quot;, Location : &quot;post&quot;, Manual : &quot;false&quot; } ; /* ]]> */   </script> <script type= 'text/javascript' src= 'http://localhost:8888/ronalfy/wp-content/plugins/wp-grins-lite/js/wp-grins.js?ver=1' ></script> The resulting HTML source: jQuery ( document ) .ready ( function () { alert ( wpgrins.Ajax_Url ) ; }) ; Localization used in JavaScript
  • 12. WordPress and Ajax Foundation » Loading Styles » wp_enqueue_style WordPress function: wp_enqueue_style prevents duplicate styles and allows for a predictable loading order via dependencies <?php wp_enqueue_style ( 'handle' , 'src' , 'deps' , 'ver' , 'media' ) ; ?> handle - Unique name for the style src - Location of the style deps - Array of dependencies (uses handler names) ver - Version of the style (string) media - Media type the stylesheet is defined for (e.g., screen, print, all) wp_enqueue_style ( 'my_css' , plugins_url ( 'my_plugin/my_css.css' ) , array ( 'another_css_file' ) , '1.0.0' , 'screen' ) ;
  • 13. WordPress and Ajax Foundation » Loading Styles » wp_print_styles WordPress action: wp_print_styles allows you to print styles for the front-end and admin area <?php add_action ( 'wp_print_styles' , 'my_styles_callback' ) ; function my_styles_callback () { wp_enqueue_style ( 'my_css' , plugins_url ( 'my_plugin/my_css.css' ) , array ( 'another_css_file' ) , '1.0.0' , 'screen' ) ; } ?> Function name needs to be unique
  • 14. WordPress and Ajax Foundation » Loading Styles » admin_print_styles WordPress action: admin_print_styles allows you to print styles for the admin area <?php add_action ( 'admin_print_styles' , 'admin_styles_callback' ) ; function admin_styles_callback () { wp_enqueue_style ( 'my_css' , plugins_url ( 'my_plugin/my_css.css' ) , array ( 'another_css_file' ) , '1.0.0' , 'screen' ) ; } ?> Function name needs to be unique
  • 15. WordPress and Ajax Foundation » Page Detection What is page detection? Allows scripts and styles to load only when needed. Why is page detection important? Helps loading time Prevents script and style conflicts It’s just the right thing to do
  • 16. WordPress and Ajax Foundation » Page Detection » Front-end WordPress Conditionals quick functions that alert you to a specific page, post type, or area of the site is_home() - Are we on the home page? is_page() - Are we on a page template? is_single() - Are we on a post template? is_admin() - Are we in the admin area? comments_open() - Are comments open for a post? And much, much more: http://codex.wordpress.org/Conditional_Tags
  • 17. WordPress and Ajax Foundation » Page Detection » Front-end Example: Loading Scripts Only When There are Comments <?php add_action ( 'wp_print_scripts' , 'my_plugin_load_scripts' ) ; function my_plugin_load_scripts () { global $post; if ( ! ( is_single () || is_page () ) || !is_object ( $post ) || $post -> comment_count == 0 ) return ; wp_enqueue_script ( 'jquery' ) ; } ?> Makes sure we’re on a post or a page Checks for the existence of the $post object (needed to get the comment count) Checks that there are comments on a post or page
  • 18. WordPress and Ajax Foundation » Page Detection » Admin Area WordPress actions: admin_print_scripts and admin_print_styles Page detection can be performed by adding the page name as a suffix for both actions - admin_print_scripts- suffix (e.g., admin_print_scripts- post.php ) - admin_print_styles- suffix (e.g., admin_print_styles- comment.php )
  • 19. WordPress and Ajax Foundation » Page Detection » Admin Area Example: Adding a Script When Editing or Creating a Post uses post.php (when editing a post) and post-new.php (when creating a post) <?php add_action ( 'admin_print_scripts-post.php' , 'my_plugin_load_scripts' ) ; add_action ( 'admin_print_scripts-post-new.php' , 'my_plugin_load_scripts' ) ; function my_plugin_load_scripts () { if ( get_post_type () == 'post' ) wp_enqueue_script ( 'jquery' ) ; } ?> Please note that admin_print_scripts and admin_print_styles use the same suffix format.
  • 20. WordPress and Ajax Foundation » Page Detection » Admin Area Example: Page Detection for a Settings Page <?php add_action ( 'admin_menu' , 'my_admin_menu' ) ; //Function to initialize the admin menu function my_admin_menu () { $page_hook = add_menu_page ( &quot;My Plugin Name Options&quot; , &quot;My Plugin&quot; , 'administrator' , 'my_plugin' , 'my_plugin_admin_settings' ) ; add_action ( &quot;admin_print_scripts-$page_hook&quot; , 'my_plugin_load_scripts' ) ; } //Build the admin menu interface function my_plugin_admin_settings () { echo &quot;My Plugin Page&quot; ; } //Load our scripts function my_plugin_load_scripts () { wp_enqueue_script ( 'jquery' ) ; } ?> When you add a menu page, the function returns a page hook you can use as a suffix for admin_print_scripts and admin_print_styles More menu hooks are available here: http://codex.wordpress.org/Adding_Administration_Menus
  • 21. WordPress and Ajax Foundation » Admin Ajax WordPress action: wp_ajax <?php add_action ( 'wp_ajax_getcomment' , 'callback_function' ) ; add_action ( 'wp_ajax_nopriv_getcomment' , 'callback_function' ) ;   function callback_function () { //process data and send Ajax response exit ; } ?> The wp_ajax WordPress action takes an Ajax action name (e.g., getcomment ) and optionally a nopriv suffix for users that aren’t logged in. More information: http://codex.wordpress.org/AJAX_in_Plugins The Ajax action is passed via JavaScript to admin-ajax.php , which alerts WordPress to run the callback function when the action is detected. A common mis-conception is that admin-ajax.php is used for just admin Ajax requests. You can use admin-ajax.php in non-admin areas as well.
  • 22. WordPress and Ajax Foundation » admin-ajax.php WordPress file: wp-admin/admin-ajax.php The admin-ajax.php file is WordPress’ built-in Ajax processer.
  • 23. WordPress and Ajax Foundation » WP_Ajax_Response WordPress class: WP_Ajax_Response <?php add_action ( 'wp_ajax_getcomment' , 'callback_function' ) ; add_action ( 'wp_ajax_nopriv_getcomment' , 'callback_function' ) ;   function callback_function () { $comment_count = wp_count_comments () ; $response = new WP_Ajax_Response () ; $response -> add ( array ( 'what' = > 'getcomments' , 'supplemental' = > array ( 'awaiting_moderation' = > number_format ( $comment_count -> moderated ) , 'approved' = > number_format ( $comment_count -> approved ) , 'spam' = > number_format ( $comment_count -> spam ) , 'trashed' = > number_format ( $comment_count -> trash ) ) )) ; $response -> send () ; exit ; } ?> The WP_Ajax_Response class is useful for returning a XML-formatted document back into JavaScript for parsing. It’s extremely useful.
  • 24. WordPress and Ajax Foundation » WP_Ajax_Response XML Format <wp_ajax> <response action = &quot;getcomment_0&quot; > <getcomments id = &quot;0&quot; position = &quot;1&quot; > <response_data> <![CDATA[]]> </response_data> <supplemental> <awaiting_moderation> <![CDATA[0]]> </awaiting_moderation> <approved> <![CDATA[2,818]]> </approved> <spam> <![CDATA[636]]> </spam> <trashed> <![CDATA[0]]> </trashed> </supplemental> </getcomments> </response> </wp_ajax> The WP_Ajax_Response class sends back an XML document for use in JavaScript
  • 25. WordPress and Ajax Foundation » WP_Ajax_Response » JavaScript Use JavaScript object: wpAjax Uses a script handler of wp-ajax-response wp_enqueue_script ( 'my_script' , get_stylesheet_directory_uri () . '/my_script.js' , array ( &quot;jquery&quot; , &quot;wp-ajax-response&quot; ) , &quot;2.3&quot; ) ; The wpAjax JavaScript class is useful for parsing the Ajax response The wp-ajax-response dependency
  • 26. WordPress and Ajax Foundation » WP_Ajax_Response » JavaScript Use Example: wpAjax parsing in JavaScript var res = wpAjax.parseAjaxResponse ( ajax_response_data ,'ajax-response' ) ; Variable res now has a structure similar to:
  • 27. WordPress and Ajax Foundation » WP_Ajax_Response » JavaScript Use Example: jQuery parsing of parsed data var res = wpAjax.parseAjaxResponse ( ajax_response_data ,'ajax-response' ) ; jQuery.each ( res.responses , function () { if (this .what == 'getcomments' ) { var moderation_count = this .supplemental.awaiting_moderation; var approved_count = this .supplemental.approved; var spam_count = this .supplemental.spam; var trashed_count = this .supplemental.trashed; } //end if }) ; //end each The wpAjax object makes it super easy to parse an Ajax response into variables
  • 28. Ajax Registration Form Let’s create an Ajax registration form
  • 29. Ajax Registration Form » Features Features we want A shortcode for inserting the form on a post or page Page detection for the shortcode No page re-loads (uses Ajax) Data validation is done via Ajax Error messages are shown via Ajax User is notified by e-mail when the registration has succeeded
  • 30. Ajax Registration Form » Plugin File Structure Registration form will be written as a plugin ajax-registration.php (main plugin file) registration.js (our script file) registration.css (the plugin’s styles)
  • 31. Ajax Registration Form » Class Structure Class structure for ajax-registration.php <?php class Ajax_Registration {   //Constructors function Ajax_Registration () { $this -> __construct () ; } function __construct () { //actions and shortcode } //Add the registration script to a page function add_scripts () { } //Add Styles for the form function add_styles () { } function ajax_process_registration () { } //end ajax_process_registration //Perform shortcode page detection function has_shortcode () { } //Add/save shortcode information function post_save ( $post_id ) { } //end post_save //Print out the shortcode function rform_shortcode ( ) { } } //end class //Instantiate $ajaxregistration = new Ajax_Registration () ; ?>
  • 32. Ajax Registration Form » Main Class » The Constructor The class constructor will add all the actions and shortcode callbacks we need function __construct () { //add scripts add_action ( 'wp_print_scripts' , array ( & $this, 'add_scripts' ) ) ; //add css add_action ( 'wp_print_styles' , array ( & $this, 'add_styles' ) ) ; //ajax add_action ( 'wp_ajax_nopriv_submitajaxregistration' , array ( & $this, 'ajax_process_registration' ) ) ; add_action ( 'wp_ajax_submitajaxregistration' , array ( & $this, 'ajax_process_registration' ) ) ; //when saving a post add_action ( 'save_post' , array ( & $this, 'post_save' ) ) ; //shortcode add_shortcode ( 'rform' , array ( & $this, 'rform_shortcode' ) ) ; } The wp_print_scripts and wp_print_styles actions are used for scripts and styles respectively The wp_ajax actions are used for a JavaScript action of submitajaxregistration The save_post action will be used to assist us in page detection A shortcode of rform is created, with a callback method of rform_shortcode
  • 33. Ajax Registration Form » Main Class » Shortcode Creation Class method: rform_shortcode Returns the form data as a string function rform_shortcode ( ) { $return = &quot;<form id='ajax-registration-form'>&quot; ; $return . = wp_nonce_field ( 'submit_ajax-registration' , '_registration_nonce' , true , false ) ; $return . = &quot;<ul id='ajax-registration-list'>&quot; ; $return . = &quot;<li><label for='firstname'>First name: </label><input type='text' size='30' name='firstname' id='firstname' /></li>&quot; ; $return . = &quot;<li><label for='lastname'>Last name: </label><input type='text' size='30' name='lastname' id='lastname' /></li>&quot; ; $return . = &quot;<li><label for='username'>Desired Username: </label><input type='text' size='30' name='username' id='username' /></li>&quot; ; $return . = &quot;<li><label for='email'>E-mail Address: </label><input type='text' size='30' name='email' id='email' /></li>&quot; ; $return . = &quot;<li><input type='submit' value='Submit Registration' name='ajax-submit' id='ajax-submit' /></li>&quot; ; $return . = &quot;<li id='registration-status-message'></li>&quot; ; $return . = &quot;</ul>&quot; ; $return . = &quot;</form>&quot; ;   return $return; } Nonce action name of _registration_nonce (will be verified later) Form ID of ajax-registration-form (used in JavaScript) Input IDs and names of firstname, lastname, username, email (used in JavaScript) Status message ID of registration-status-message (used in JavaScript)
  • 34. Ajax Registration Form » Main Class » Shortcode Creation Adding the shortcode to a post
  • 35. Ajax Registration Form » Main Class » Page Detection Class method: post_save Find out if the post has the rform shortcode, and set a custom field if so function post_save ( $post_id ) { //Retrieve the post object - If a revision, get the original post ID $revision = wp_is_post_revision ( $post_id ) ; if ( $revision ) $post_id = $revision; $post = get_post ( $post_id ) ;   //Perform a test for a shortcode in the post's content preg_match ( '/rform[^]*/is' , $post -> post_content, $matches ) ;     if ( count ( $matches ) == 0 ) { delete_post_meta ( $post_id, '_ajax_registration' ) ; } else { update_post_meta ( $post_id, '_ajax_registration' , '1' ) ; } } //end post_save Retrieve the original post ID if a revision Test the post content for the shortcode rform If the shortcode is present, set the _ajax_registration custom field. If not, remove it.
  • 36. Ajax Registration Form » Main Class » Page Detection Class method: has_shortcode A conditional that lets us know if the post has the rform shortcode or not //Returns true if a post has the rform shortcode, false if not function has_shortcode () { global $post; if ( !is_object ( $post ) ) return false ; if ( get_post_meta ( $post -> ID, '_ajax_registration' , true ) ) return true ; else return false ; } Checks for a custom field of _ajax_registration . If the custom field exists, return true . If not, return false .
  • 37. Ajax Registration Form » Main Class » Add Scripts and Localization Class method: add_scripts Add the registration script file and some JavaScript localization //Add the registration script to a page function add_scripts () { if ( is_admin () || ! $this -> has_shortcode () ) return ; wp_enqueue_script ( 'ajax-registration-js' , plugins_url ( 'js/registration.js' , __FILE__ ) , array ( 'jquery' , 'wp-ajax-response' ) , '1.0' ) ; wp_localize_script ( 'ajax-registration-js' , 'ajaxregistration' , array ( 'Ajax_Url' = > admin_url ( 'admin-ajax.php' ) ) ) ; } Uses conditionals is_admin and has_shortcode for page detection. Will only load on the front-end where the shortcode exists in the page’s content. Localizes a JavaScript object of ajaxregistration with a variable called Ajax_Url . Ajax_Url points to WordPress’ admin-ajax.php , which we’ll need to make our Ajax request in JavaScript.
  • 38. Ajax Registration Form » Main Class » Add Styles Class method: add_styles Add the registration CSS file function add_styles () { if ( is_admin () || ! $this -> has_shortcode () ) return ; wp_enqueue_style ( 'ajax-registration-css' , plugins_url ( 'css/registration.css' , __FILE__ ) ) ; } Uses conditionals is_admin and has_shortcode for page detection. Will only load on the front-end where the shortcode exists in the page’s content.
  • 39. Ajax Registration Form » Main Class » The Ajax Processor Class method: ajax_process_registration Processes the Ajax request and returns an Ajax response function ajax_process_registration () { //Verify the nonce check_ajax_referer ( 'submit_ajax-registration' ) ;   exit ;   } //end ajax_process_registration The first thing we do in the Ajax processor is check the passed nonce. The nonce is checked with check_ajax_referer . The nonce action named submit_ajax-registration was set in the rform_shortcode method. The JavaScript file is responsible for setting a $_POST variable called _ajax_nonce , which is what check_ajax_referer checks for.
  • 40. Ajax Registration Form » Main Class » ajax_process_registration Parsing the data //Need registration.php for data validation require_once ( ABSPATH . WPINC . '/registration.php' ) ;   //Get post data if ( !isset ( $_POST [ 'ajax_form_data' ] ) ) die ( &quot;-1&quot; ) ; parse_str ( $_POST [ 'ajax_form_data' ] , $form_data ) ; The WordPress file registration.php is included (includes such functions as validate_username and username_exists ) Checks for $_POST variable ajax_form_data (the JavaScript file will set this variable) Parses the data into the $form_data array via parse_str $form_data['firstname'] $form_data['lastname'] $form_data['email'] $form_data['username']
  • 41. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Sanitizing the entries Uses the sanitize_text_field function to sanitize the form inputs //Get the form fields $firstname = sanitize_text_field ( $form_data [ 'firstname' ] ) ; $lastname = sanitize_text_field ( $form_data [ 'lastname' ] ) ; $username = sanitize_text_field ( $form_data [ 'username' ] ) ; $email = sanitize_text_field ( $form_data [ 'email' ] ) ;   $error_response = $success_response = new WP_Ajax_Response () ; $errors = new WP_Error () ; Uses the sanitize_text_field WordPress function to sanitize the form inputs Instantiates an instance of WP_Ajax_Response (for sending the Ajax responses) Instantiates an instance of WP_Error (used as part of the Ajax response)
  • 42. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Checking required entries We’ll use the WP_Error instance to add any errors if any fields are empty //Start data validation on firstname/lastname //Check required fields if ( empty ( $firstname ) ) $errors -> add ( 'firstname' , 'You must fill out a first name.' , 'firstname' ) ;   if ( empty ( $lastname ) ) $errors -> add ( 'lastname' , 'You must fill out a last name.' ) ;   if ( empty ( $username ) ) $errors -> add ( 'username' , 'You must fill out a user name.' ) ;   if ( empty ( $email ) ) $errors -> add ( 'email' , 'You must fill out an e-mail address.' ) ; The first argument in $errors->add is an error code. However, the code also doubles for the form input ID that will be used in JavaScript.
  • 43. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: If any errors, send a response We’ll be using the WP_Ajax_Response instance to return a response if errors are present //If required fields aren't filled out, send response if ( count ( $errors -> get_error_codes () ) > 0 ) { $error_response -> add ( array ( 'what' = > 'errors' , 'id' = > $errors )) ; $error_response -> send () ; exit ; } The WP_Error get_error_codes method is used to determine if there are any errors saved If there are errors, we build the Ajax response using fields what and id The id portion allows for a WP_Error object
  • 44. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Check for a valid username //Add usernames we don't want used $invalid_usernames = array ( 'admin' ) ; //Do username validation $username = sanitize_user ( $username ) ; if ( ! validate_username ( $username ) || in_array ( $username, $invalid_usernames ) ) { $errors -> add ( 'username' , 'Username is invalid.' ) ; } if ( username_exists ( $username ) ) { $errors -> add ( 'username' , 'Username already exists.' ) ; } Username is further sanitized via the sanitize_user WordPress function The $invalid_usernames array can contain usernames you don’t want users to select. If the username isn’t valid (via the validate_username function) or a username is reserved, we add an error - If the username already exists (via the username_exists function), we add an error
  • 45. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: Check for a valid e-mail address //Do e-mail address validation if ( ! is_email ( $email ) ) { $errors -> add ( 'email' , 'E-mail address is invalid.' ) ; } if ( email_exists ( $email )) { $errors -> add ( 'email' , 'E-mail address is already in use.' ) ; } If the e-mail address is invalid (via the is_email function), we add an error If the e-mail address already exists (via the email_exists function), we add an error
  • 46. Ajax Registration Form » Main Class » ajax_process_registration Data Validation: If any further errors, send a response We’ll be using the WP_Ajax_Response instance to return a response if errors are present //If required fields aren't filled out, send response if ( count ( $errors -> get_error_codes () ) > 0 ) { $error_response -> add ( array ( 'what' = > 'errors' , 'id' = > $errors )) ; $error_response -> send () ; exit ; } We have to assume that all fields aren’t empty at this point Only invalid username/email errors will be sent
  • 47. Ajax Registration Form » Main Class » ajax_process_registration Create the User Object All data has been validated. Create the User object. //Everything has been validated, proceed with creating the user //Create the user $user_pass = wp_generate_password () ; $user = array ( 'user_login' = > $username, 'user_pass' = > $user_pass, 'first_name' = > $firstname, 'last_name' = > $lastname, 'user_email' = > $email ) ; $user_id = wp_insert_user ( $user ) ; A user password is generated (via wp_generate_password ) A $user array is created with fields user_login , user_pass , first_name , last_name , and user_email User is created by passing the $user array to function wp_insert_user Function wp_insert_user returns the new user’s ID
  • 48. Ajax Registration Form » Main Class » ajax_process_registration Send the Registration E-mail User has been created. Send a registration e-mail. /*Send e-mail to admin and new user - You could create your own e-mail instead of using this function*/ wp_new_user_notification ( $user_id, $user_pass ) ; A user e-mail is sent by passing the variables $user_id and $user_pass to the wp_new_user_notification function You could skip this step and instead create a custom e-mail (using wp_mail )
  • 49. Ajax Registration Form » Main Class » ajax_process_registration Sending the Ajax Response User has been created. Let’s send back an Ajax response. //Send back a response $success_response -> add ( array ( 'what' = > 'object' , 'data' = > 'User registration successful. Please check your e-mail.' )) ; $success_response -> send () ; exit ; } //end ajax_process_registration The data field in the Ajax response is used for sending a string message back to JavaScript. This message will be used in our form’s status area.
  • 50. Ajax Registration Form » The CSS » registration.css Adding the CSS Code Code will go into the registration.css file #ajax-registration-list { list-style-type : none ; } #ajax-registration-list label { display : block ; } #ajax-registration-form .error { background-color : #FFEBE8 ; border : 1px solid #CC0000 ; } #ajax-registration-form .success { background-color : #FFFFE0 ; border : 1px solid #E6DB55 ; } Basic CSS is used here for the form layout and the error/status messages.
  • 51. Ajax Registration Form » The JavaScript » registration.js JavaScript structure A jQuery namespace called registrationform is used jQuery ( document ) .ready ( function () { var $ = jQuery; $.registrationform = { init : function () {   } } ; //end .registrationform $.registrationform.init () ; }) ; - A jQuery object named registrationform is created Within the registrationform object, a there is a placeholder function named init The function is initialized by calling $.registrationform.init
  • 52. Ajax Registration Form » The JavaScript » registration.js JavaScript function: init - Capturing the submit event The form has an ID of ajax-registration-form, which we’ll use to capture the submit event init : function () { $ ( &quot;#ajax-registration-form&quot; ) . submit ( function () { return false ; }) ; } The form ID ( ajax-registration-form ) is used with the jQuery submit event.
  • 53. Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Clearing any error messages In the event the form has previously been submitted, we’ll need to clear all previous messages $ ( &quot;#ajax-registration-form&quot; ) . submit ( function () { //Clear all form errors $ ( '#ajax-registration-form input' ) .removeClass ( 'error' ) ; //Update status message $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'error' ) .addClass ( 'success' ) .html ( 'Sending...' ) ; //Disable submit button $ ( '#ajax-submit' ) .attr ( &quot;disabled&quot;, &quot;disabled&quot; ) ;   return false ; }) ; All form inputs are cleared of errors (by removing the error CSS class) The status message (with ID of registration-status-message ) is updated with the success CSS class and given the text “Sending…” The submit button (with ID ajax-submit ) is disabled so the user can’t click it again during the submission process
  • 54. Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Parse the Form Data We’ll use jQuery to parse the form data into a string we can pass via Ajax //Disable submit button $ ( '#ajax-submit' ) .attr ( &quot;disabled&quot;, &quot;disabled&quot; ) ; //Serialize form data var form_data = $ ( '#ajax-registration-form input' ) .serializeArray () ; form_data = $.param ( form_data ) ; return false ; All form inputs are captured and serialized to an array via the serializeArray function The serialized form data is then converted to a url-encoded string via the param function. The form_data variable now has a value similar to: _registration_nonce=0ca8be2b7b&firstname=Ronald&lastname=Huereca&username=ronalfy&email=ron%40ronalfy.com
  • 55. Ajax Registration Form » The JavaScript » registration.js Form Submit Event: Submit the Ajax Request form_data = $.param ( form_data ) ; //Submit ajax request $.post ( ajaxregistration.Ajax_Url , { action : 'submitajaxregistration', ajax_form_data : form_data , _ajax_nonce : $ ( '#_registration_nonce' ) .val () } , function ( data ){ //Success code goes here } ) ; return false ; The jQuery post function acts as an Ajax POST event We pass it the URL to WordPress’ admin-ajax.php file (via localized JavaScript variable ajaxregistration.Ajax_Url ) The Ajax action submitajaxregistration is used for the WordPress wp_ajax action A post variable named ajax_form_data contains all our form data A post variable named _ajax_nonce contains the form’s nonce Finally, a callback method is created to handle the Ajax response (the response will be held in the data variable)
  • 56. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response function ( data ){ var res = wpAjax.parseAjaxResponse ( data , 'ajax-response' ) ; if ( res.errors ) { //errors } else { //no errors } } Data is parsed via the parseAjaxResponse function If errors are detected, spit out errors If no errors are detected, display a success mesage
  • 57. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The parsed data (if errors are detected)
  • 58. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The errors data
  • 59. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - The errors data Iterate through each response, and iterate through each error within the response if ( res.errors ) { //form errors //re-enable submit button $ ( '#ajax-submit' ) .removeAttr ( &quot;disabled&quot; ) ; var html = '' ; $.each ( res.responses , function () { $.each (this .errors , function () { $ ( &quot;#&quot; + this .code ) .addClass ( 'error' ) ; html = html + this .message + '<br />' ; }) ; }) ; $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'success' ) .addClass ( 'error' ) .html ( html ) ; } There could be multiple responses, so we iterate through each one Within each response are several errors, so we iterate through those and build an HTML string with all of the error messages Furthermore, since each error has a code that identifies the form input , we add an error class (via CSS) to show that there is an error Finally, we update our status message with the errors
  • 60. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Example Output If there are any errors, this is what you might see
  • 61. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Success If there are no errors, we parse the data in the success portion of the conditional } else { //no errors $.each ( res.responses , function () { $ ( &quot;#registration-status-message&quot; ) .addClass ( 'success' ) .html (this .data ) ; return ; }) ; } There could be multiple responses, so we iterate through each one Output the success message (via the this.data variable)
  • 62. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Success Output If there aren’t any errors, this is what you might see
  • 63. Ajax Registration Form » The JavaScript » registration.js Parsing the Ajax Response - Full Function Code function ( data ){ var res = wpAjax.parseAjaxResponse ( data , 'ajax-response' ) ; if ( res.errors ) { //form errors //re-enable submit button $ ( '#ajax-submit' ) .removeAttr ( &quot;disabled&quot; ) ; var html = '' ; $.each ( res.responses , function () { $.each (this .errors , function () { $ ( &quot;#&quot; + this .code ) .addClass ( 'error' ) ; html = html + this .message + '<br />' ; }) ; }) ; $ ( &quot;#registration-status-message&quot; ) .removeClass ( 'success' ) .addClass ( 'error' ) .html ( html ) ; } else { //no errors $.each ( res.responses , function () { $ ( &quot;#registration-status-message&quot; ) .addClass ( 'success' ) .html (this .data ) ; return ; }) ; } } Eat your heart out.
  • 64. Conclusion » The Code Download link The sample Ajax registration form plugin can be found at: http://www.wpajax.com/code
  • 65. Conclusion » Want to Know More? What to know more? Buy my damn book! http://www.wpajax.com
  • 66. Conclusion » Want to Know More? What to know more? Buy my damn book! I mean, pretty please, buy my book. http://www.wpajax.com
  • 67. Conclusion » WordPress and Ajax » The End - Twitter @ronalfy - Skype ronalfy - Personal site (rants and musings) http://www.ronalfy.com - WordPress and Ajax e-book http://www.wpajax.com That’s it! Thank you for your time. - Ajax Edit Comments http://www.ajaxeditcomments.com - WebDevStudios http://www.webdevstudios.com