SlideShare a Scribd company logo
1 of 51
Download to read offline
WordPress + Ajax
                                 recipes for the road




                           WordCamp Reno Tahoe 2012

Saturday, June 30, 2012
Dylan Kuhn

            Freelance WordPress Hacker




            http://www.cyberhobo.net
            @dylankuhn on Twitter



Saturday, June 30, 2012
Perspective
           Empower small organizations with WordPress
           Usually the sole coder
           Years of experience - coding in a camper




Saturday, June 30, 2012
Ajax isn’t Ajax


Saturday, June 30, 2012
A synchronous    missing server push? threads?




         J avaScript      or jQuery. or...
                          d3js? CoffeeScript?




         A nd             wat?




         X ML             Mm. Text works. Mucho JSON. It’s your
                          data, but must be HTTP friendly.


Saturday, June 30, 2012
So what is it?
         It’s about what the web is made of.

         HTML: Documents


         +Javascript: Self-Contained Apps

         +Ajax: Connected Apps
Saturday, June 30, 2012
Insert Complicated Browser-Server Diagram Here

                                                Or Say




         With Ajax we can request more
           data after the page loads

                           so you can make it infinitely more delicious :)

Saturday, June 30, 2012
Unfortunately

                          apps are harder to write

                               Fortunately

   WordPress gives us tools
Saturday, June 30, 2012
JavaScript libraries
        jQuery, Scriptalicious, Prototype

        Client script handling
         wp_register_script(), wp_enqueue_script()

         Server request handling hooks
         wp_ajax_$action, wp_ajax_nopriv_$action

        XML generation class
         WP_Ajax_Response


Saturday, June 30, 2012
Recipe: Ajax Hello Dolly

         Ingredients:

         Fresh WordPress install
         Hello Dolly plugin
         Instant TwentyEleven child theme
         A back end jQuery script
         A few theme (or plugin) functions

Saturday, June 30, 2012
Prep


                          Install WordPress

                          Activate the Hello Dolly Plugin




Saturday, June 30, 2012
Instant Child Theme


            $ cd wp-content/themes   # in the themes folder
            $ mkdir recipes-child    # make a new folder
            $ cd recipes-child       # where we’ll add files




Saturday, June 30, 2012
Instant Child Theme
          Create a theme file style.css:
          /*
          Theme Name: Ajax Recipes Child
          Description: Twenty Eleven child for Ajax recipes
          Author: Dylan Kuhn
          Template: twentyeleven
          */

          @import url("../twentyeleven/style.css");


           Activate your new theme :)

Saturday, June 30, 2012
themes
                          !"" index.php
                          !"" recipes-child
                          #   $"" style.css
                          !"" twentyeleven
                          ...
                          $"" twentyten




Saturday, June 30, 2012
Back End Script
                          Create a theme file hello-admin.js:
                          jQuery( function( $ ) {
                            var $dolly = $( '#dolly' );

                            $dolly.click( function() {

                              $dolly.html( 'loading...' );

                               $.ajax( {
                                 url: ajaxurl,
                                 data: { action: 'hello_dolly' },
                                 dataType: 'text',
                                 success: function( lyric ) {
                                    $dolly.html( lyric );
                                 }
                               } );
                            } );
                          } );

Saturday, June 30, 2012
themes
                          !"" index.php
                          !"" recipes-child
                          #   !"" hello-admin.js
                          #   $"" style.css
                          !"" twentyeleven
                          ...
                          $"" twentyten




Saturday, June 30, 2012
Simple Theme Namespace
          Create a theme file functions.php:
          <?php

          // Pattern: static class as PHP 5.2 namespace

          AjaxRecipesTheme::load();

          class AjaxRecipesTheme {

                static function load() {
                  // We'll call add_action and add_filter here
                }

                // More static methods will go here

          }
Saturday, June 30, 2012
Enqueue Back End Script
          Register a method to call when admin scripts can be queued

          class AjaxRecipesTheme {

                static function load() {

                          add_action(
                             'admin_enqueue_scripts',
                             array(
                               __CLASS__,
                               'action_admin_enqueue_scripts'
                             )
                          );

            }
          ...
          }
Saturday, June 30, 2012
Enqueue Back End Script
       Implement a method to include our hello-admin.js script
       class AjaxRecipesTheme {
       ...
         static function action_admin_enqueue_scripts() {

                    wp_enqueue_script(
                       'ajax-recipes-hello-admin',
                       get_stylesheet_directory_uri() . '/hello-admin.js',
                       array( 'jquery' ),
                       false,
                       true
                    );

         }
       ...
       }


Saturday, June 30, 2012
Register a method to handle Ajax Dolly requests

                          class AjaxRecipesTheme {

                            static function load() {
                          ...
                              add_action(
                                 'wp_ajax_hello_dolly',
                                 array(
                                   __CLASS__,
                                   'action_wp_ajax_hello_dolly'
                                 )
                              );

                            }
                          ...
                          }

Saturday, June 30, 2012
Add the method to handle Ajax Dolly requests


       class AjaxRecipesTheme {
       ...
         static function action_wp_ajax_hello_dolly() {
           exit( hello_dolly_get_lyric() );
         }
       ...
       }




Saturday, June 30, 2012
Ready to Serve!
                          themes
                          !"" index.php
                          !"" recipes-child
                          #   !"" hello-admin.js
                          #   !"" functions.php
                          #   $"" style.css
                          !"" twentyeleven
                          ...
                          $"" twentyten



Saturday, June 30, 2012
And the back end looks...
                     exactly the same as before
                          but! and this is my but:




Saturday, June 30, 2012
What is it doing in there?




Saturday, June 30, 2012
Nice!
                   But will Dolly be listening?
                        In the back end?
                        To that tiny but?


Saturday, June 30, 2012
Recipe: Hello Dolly, World!

                   Ingredients:

                   Ajax Hello Dolly
                   A new page and template
                   One more hook




Saturday, June 30, 2012
Prep



                 Create a new page titled “Are You Dolly?”




                          (we’ll assume it gets the default slug are-you-dolly)


Saturday, June 30, 2012
Mark It Up
      create theme file page-are-you-dolly.php:
     <?php get_header(); ?>

     <div id="primary">
        <div id="content" role="main">

                  <h1 class="entry-title">Are You Dolly?</h1>

                  <button id="ajax-recipe-impersonate-dolly">I'm Dolly</button>

                  <p id="ajax-recipe-dolly-message">
                  If you're Dolly, I have a message for you.
                  </p>

        </div><!-- #content -->
     </div><!-- #primary -->

     <?php get_footer(); ?>


Saturday, June 30, 2012
Inline JavaScript
          For now we’ll add a script to page-are-you-dolly.php:
        <script>
        jQuery( function( $ ) {
          var $message = $( '#ajax-recipe-dolly-message' );

               $( '#ajax-recipe-impersonate-dolly' ).click( function() {
                 $message.html( '...' );
                 $.ajax( {
                    url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
                    data: { action: 'hello_dolly' },
                    dataType: 'text',
                    success: function( data ) {

                          $message.html( data );

               }
             } );
          } );
        } );
        </script>
        <?php get_footer(); ?>
Saturday, June 30, 2012
Gimme jQuery
       On the front end, we have to ask for it

       As of WordPress 3.3, we can do this in page-are-you-dolly.php:

          <?php wp_enqueue_script( 'jquery' ); ?>

          <?php get_header() ?>
          ...




Saturday, June 30, 2012
Let the Front End In
                          A different ajax action fires for non-logged-in users

                          class AjaxRecipesTheme {

                            static function load() {
                          ...
                              add_action(
                                 'wp_ajax _nopriv    _hello_dolly',
                                 array(
                                   __CLASS__,
                                   'action_wp_ajax_hello_dolly'
                                 )
                              );

                            }
                          ...
                          }

Saturday, June 30, 2012
Sing it




Saturday, June 30, 2012
Refinement: Spider Garnish


                   Ingredients:

                   1 spider
                   template tweaks




Saturday, June 30, 2012
Spider




                          (a.k.a. web spinner)

Saturday, June 30, 2012
Drop your spider in the theme
                          themes
                          !"" index.php
                          !"" recipes-child
                          #   !"" hello-admin.js
                          #   !"" functions.php
                          #   !"" spinner.gif
                          #   $"" style.css
                          !"" twentyeleven
                          ...
                          $"" twentyten



Saturday, June 30, 2012
Load the spider
      in page-are-you-dolly.php:


     <button id="ajax-recipe-impersonate-dolly">I'm Dolly</button>

     <p id="ajax-recipe-spinner" style="display:none;">
       <img src="<?php
          echo get_stylesheet_directory_uri(); ?>/spinner.gif"
          alt="..." />
     </p>

     <p id="ajax-recipe-dolly-message">
     If you're Dolly, I have a message for you.
     </p>




Saturday, June 30, 2012
Show and hide the spider
      in page-are-you-dolly.php:
     var $message = $( '#ajax-recipe-dolly-message' ),
       $spinner = $( '#ajax-recipe-spinner' );

     $( '#ajax-recipe-impersonate-dolly' ).click( function() {
       $message.hide();
       $spinner.show();
       $.ajax( {
          url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',
          data: { action: 'hello_dolly' },
          dataType: 'text',
          success: function( data ) {

                          $spinner.hide();
                          $message.show().html( data );

                  }

Saturday, June 30, 2012
Onto Our Tuffet




Saturday, June 30, 2012
Recipe: Spider Ghoulash


                   Ingredients:

                   many spiders




Saturday, June 30, 2012
Saturday, June 30, 2012
Spider Ghoulash




Saturday, June 30, 2012
A Cry for Reason
         David DeSandro / Metafizzy
         creator of the ultra-cool isotope library
         pleads:

         “Isotope enables a wealth of functionality. But just because
         you can take advantage of its numerous features together,
         doesn’t mean you necessarily should. For each each feature
         you implement with Isotope, consider the benefit gained by
         users, at the cost of another level of complexity to your
         interface.”


Saturday, June 30, 2012
Saturday, June 30, 2012
Programmer? Maybe ask the users.
                  Users? Maybe show them the ghoulash.
                  Everyone? Maybe AJAX ALL THE THINGS!
Saturday, June 30, 2012
Refinement: Script File

                   Ingredients:

                   a separate script file
                   enqueueing server code
                   configuration server code




Saturday, June 30, 2012
Cut the Inline Script
          Create a new theme file hello.js
          Copy the <script> contents in page-are-you-dolly.php
          Paste the code into hello.js
          Remove entire <script> from page-are-you-dolly.php

                     page-are-you-dolly.php


                          inline javascript

                                                hello.js



Saturday, June 30, 2012
themes
                          !"" index.php
                          !"" recipes-child
                          #   !"" hello.js
                          #   !"" hello-admin.js
                          #   !"" functions.php
                          #   !"" spinner.gif
                          #   $"" style.css
                          !"" twentyeleven
                          ...
                          $"" twentyten



Saturday, June 30, 2012
We’ll expand this call in page-are-you-dolly.php:

       <?php wp_enqueue_script( 'jquery' ); ?>

       to load both jQuery and our new hello script:

       <?php
       wp_enqueue_script(
          'ajax-recipes-hello',
          get_stylesheet_directory_uri() . '/hello.js',
          array( 'jquery' ),
          false,
          true
       );
       ?>

Saturday, June 30, 2012
Unmix It
       We need to get rid of the PHP code in hello.js:
       url: '<?php echo admin_url( 'admin-ajax.php' ); ?>',

       We can get that URL into a JavaScript variable (trust me):
       $.ajax( {
         url: ajaxRecipesConfig.ajaxurl,
         data: { action: 'hello_dolly' },
         dataType: 'text',
         success: function( data ) {

                   $spinner.hide();
                   $message.show().html( data );

         }
       } );
Saturday, June 30, 2012
Localize? Sort of.
        wp_localize_script() will create our variable for us.
        Back in page-are-you-dolly.php:
        wp_enqueue_script(
           'ajax-recipes-hello',
        ...
        );

         $hello_config = array(
            'ajaxurl' => admin_url( 'admin-ajax.php' )
         );

         wp_localize_script(
            'ajax-recipes-hello',
            'ajaxRecipesConfig',
            $hello_config
         );
Saturday, June 30, 2012
That’s It!
                                           Go forth and Ajax

                          http://2012.reno.wordcamp.org/session/wordpress-ajax-recipes/


                                https://github.com/cyberhobo/wp-ajax-dolly-theme


                                           cyberhobo@cyberhobo.net



                                                  Thanks!


                              WordCamp Reno Tahoe 2012

Saturday, June 30, 2012

More Related Content

What's hot

Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do MoreRemy Sharp
 
jQuery Features to Avoid
jQuery Features to AvoidjQuery Features to Avoid
jQuery Features to Avoiddmethvin
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoRob Bontekoe
 
Como escalar aplicações PHP
Como escalar aplicações PHPComo escalar aplicações PHP
Como escalar aplicações PHPAugusto Pascutti
 
Reactive Type-safe WebComponents
Reactive Type-safe WebComponentsReactive Type-safe WebComponents
Reactive Type-safe WebComponentsMartin Hochel
 
jQuery('#knowledge').appendTo('#you');
jQuery('#knowledge').appendTo('#you');jQuery('#knowledge').appendTo('#you');
jQuery('#knowledge').appendTo('#you');mikehostetler
 
Stack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for DevelopersStack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for DevelopersJonathan Sharp
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testingsmontanari
 
The Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J QueryThe Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J QueryQConLondon2008
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009Remy Sharp
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Thinqloud
 
Dojo >= 1.7 Kickstart
Dojo >= 1.7  KickstartDojo >= 1.7  Kickstart
Dojo >= 1.7 KickstartHazem Saleh
 
01 Introduction - JavaScript Development
01 Introduction - JavaScript Development01 Introduction - JavaScript Development
01 Introduction - JavaScript DevelopmentTommy Vercety
 
JavaScript Code Organizations, Patterns Slides - Zach Dennis
JavaScript Code Organizations, Patterns Slides - Zach DennisJavaScript Code Organizations, Patterns Slides - Zach Dennis
JavaScript Code Organizations, Patterns Slides - Zach DennisZach Dennis
 
New text documentfsdfs
New text documentfsdfsNew text documentfsdfs
New text documentfsdfsAh Lom
 

What's hot (20)

Write Less Do More
Write Less Do MoreWrite Less Do More
Write Less Do More
 
jQuery Features to Avoid
jQuery Features to AvoidjQuery Features to Avoid
jQuery Features to Avoid
 
Jquery
JqueryJquery
Jquery
 
Building iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" DominoBuilding iPhone Web Apps using "classic" Domino
Building iPhone Web Apps using "classic" Domino
 
Como escalar aplicações PHP
Como escalar aplicações PHPComo escalar aplicações PHP
Como escalar aplicações PHP
 
Reactive Type-safe WebComponents
Reactive Type-safe WebComponentsReactive Type-safe WebComponents
Reactive Type-safe WebComponents
 
jQuery('#knowledge').appendTo('#you');
jQuery('#knowledge').appendTo('#you');jQuery('#knowledge').appendTo('#you');
jQuery('#knowledge').appendTo('#you');
 
Web2.0 with jQuery in English
Web2.0 with jQuery in EnglishWeb2.0 with jQuery in English
Web2.0 with jQuery in English
 
Stack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for DevelopersStack Overflow Austin - jQuery for Developers
Stack Overflow Austin - jQuery for Developers
 
Single page webapps & javascript-testing
Single page webapps & javascript-testingSingle page webapps & javascript-testing
Single page webapps & javascript-testing
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 
The Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J QueryThe Dom Scripting Toolkit J Query
The Dom Scripting Toolkit J Query
 
jQuery
jQueryjQuery
jQuery
 
jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009jQuery Loves Developers - Oredev 2009
jQuery Loves Developers - Oredev 2009
 
Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...Learning jQuery made exciting in an interactive session by one of our team me...
Learning jQuery made exciting in an interactive session by one of our team me...
 
Dojo >= 1.7 Kickstart
Dojo >= 1.7  KickstartDojo >= 1.7  Kickstart
Dojo >= 1.7 Kickstart
 
01 Introduction - JavaScript Development
01 Introduction - JavaScript Development01 Introduction - JavaScript Development
01 Introduction - JavaScript Development
 
JavaScript Code Organizations, Patterns Slides - Zach Dennis
JavaScript Code Organizations, Patterns Slides - Zach DennisJavaScript Code Organizations, Patterns Slides - Zach Dennis
JavaScript Code Organizations, Patterns Slides - Zach Dennis
 
New text documentfsdfs
New text documentfsdfsNew text documentfsdfs
New text documentfsdfs
 
D3.js and SVG
D3.js and SVGD3.js and SVG
D3.js and SVG
 

Similar to WordPress + Ajax recipes for the road

Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentationMevin Mohan
 
Drupal Javascript for developers
Drupal Javascript for developersDrupal Javascript for developers
Drupal Javascript for developersDream Production AG
 
Introduction to j query
Introduction to j queryIntroduction to j query
Introduction to j querythewarlog
 
jQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPagesjQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPagesMark Roden
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutesSimon Willison
 
Jquery tutorial
Jquery tutorialJquery tutorial
Jquery tutorialBui Kiet
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowkatbailey
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowWork at Play
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery FundamentalsGil Fink
 
JavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQueryJavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQuerykatbailey
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringIngo Schommer
 
A test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileA test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileGlobalLogic Ukraine
 
Intro To jQuery In Drupal
Intro To jQuery In DrupalIntro To jQuery In Drupal
Intro To jQuery In DrupalMatthew Farina
 

Similar to WordPress + Ajax recipes for the road (20)

Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
Introduction to jQuery
Introduction to jQueryIntroduction to jQuery
Introduction to jQuery
 
J query intro_29thsep_alok
J query intro_29thsep_alokJ query intro_29thsep_alok
J query intro_29thsep_alok
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
Drupal Javascript for developers
Drupal Javascript for developersDrupal Javascript for developers
Drupal Javascript for developers
 
Introduction to j query
Introduction to j queryIntroduction to j query
Introduction to j query
 
jQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPagesjQuery - the world's most popular java script library comes to XPages
jQuery - the world's most popular java script library comes to XPages
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
Jquery tutorial
Jquery tutorialJquery tutorial
Jquery tutorial
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
JavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to knowJavaScript in Drupal 7: What developers need to know
JavaScript in Drupal 7: What developers need to know
 
jQuery Fundamentals
jQuery FundamentalsjQuery Fundamentals
jQuery Fundamentals
 
JavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQueryJavaScript the Smart Way - Getting Started with jQuery
JavaScript the Smart Way - Getting Started with jQuery
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
Jquery
JqueryJquery
Jquery
 
jQuery
jQueryjQuery
jQuery
 
SilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript RefactoringSilverStripe CMS JavaScript Refactoring
SilverStripe CMS JavaScript Refactoring
 
A test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobileA test framework out of the box - Geb for Web and mobile
A test framework out of the box - Geb for Web and mobile
 
WCLA12 JavaScript
WCLA12 JavaScriptWCLA12 JavaScript
WCLA12 JavaScript
 
Intro To jQuery In Drupal
Intro To jQuery In DrupalIntro To jQuery In Drupal
Intro To jQuery In Drupal
 

Recently uploaded

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 

Recently uploaded (20)

Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 

WordPress + Ajax recipes for the road

  • 1. WordPress + Ajax recipes for the road WordCamp Reno Tahoe 2012 Saturday, June 30, 2012
  • 2. Dylan Kuhn Freelance WordPress Hacker http://www.cyberhobo.net @dylankuhn on Twitter Saturday, June 30, 2012
  • 3. Perspective Empower small organizations with WordPress Usually the sole coder Years of experience - coding in a camper Saturday, June 30, 2012
  • 5. A synchronous missing server push? threads? J avaScript or jQuery. or... d3js? CoffeeScript? A nd wat? X ML Mm. Text works. Mucho JSON. It’s your data, but must be HTTP friendly. Saturday, June 30, 2012
  • 6. So what is it? It’s about what the web is made of. HTML: Documents +Javascript: Self-Contained Apps +Ajax: Connected Apps Saturday, June 30, 2012
  • 7. Insert Complicated Browser-Server Diagram Here Or Say With Ajax we can request more data after the page loads so you can make it infinitely more delicious :) Saturday, June 30, 2012
  • 8. Unfortunately apps are harder to write Fortunately WordPress gives us tools Saturday, June 30, 2012
  • 9. JavaScript libraries jQuery, Scriptalicious, Prototype Client script handling wp_register_script(), wp_enqueue_script() Server request handling hooks wp_ajax_$action, wp_ajax_nopriv_$action XML generation class WP_Ajax_Response Saturday, June 30, 2012
  • 10. Recipe: Ajax Hello Dolly Ingredients: Fresh WordPress install Hello Dolly plugin Instant TwentyEleven child theme A back end jQuery script A few theme (or plugin) functions Saturday, June 30, 2012
  • 11. Prep Install WordPress Activate the Hello Dolly Plugin Saturday, June 30, 2012
  • 12. Instant Child Theme $ cd wp-content/themes # in the themes folder $ mkdir recipes-child # make a new folder $ cd recipes-child # where we’ll add files Saturday, June 30, 2012
  • 13. Instant Child Theme Create a theme file style.css: /* Theme Name: Ajax Recipes Child Description: Twenty Eleven child for Ajax recipes Author: Dylan Kuhn Template: twentyeleven */ @import url("../twentyeleven/style.css"); Activate your new theme :) Saturday, June 30, 2012
  • 14. themes !"" index.php !"" recipes-child #   $"" style.css !"" twentyeleven ... $"" twentyten Saturday, June 30, 2012
  • 15. Back End Script Create a theme file hello-admin.js: jQuery( function( $ ) { var $dolly = $( '#dolly' ); $dolly.click( function() { $dolly.html( 'loading...' ); $.ajax( { url: ajaxurl, data: { action: 'hello_dolly' }, dataType: 'text', success: function( lyric ) { $dolly.html( lyric ); } } ); } ); } ); Saturday, June 30, 2012
  • 16. themes !"" index.php !"" recipes-child #   !"" hello-admin.js #   $"" style.css !"" twentyeleven ... $"" twentyten Saturday, June 30, 2012
  • 17. Simple Theme Namespace Create a theme file functions.php: <?php // Pattern: static class as PHP 5.2 namespace AjaxRecipesTheme::load(); class AjaxRecipesTheme { static function load() { // We'll call add_action and add_filter here } // More static methods will go here } Saturday, June 30, 2012
  • 18. Enqueue Back End Script Register a method to call when admin scripts can be queued class AjaxRecipesTheme { static function load() { add_action( 'admin_enqueue_scripts', array( __CLASS__, 'action_admin_enqueue_scripts' ) ); } ... } Saturday, June 30, 2012
  • 19. Enqueue Back End Script Implement a method to include our hello-admin.js script class AjaxRecipesTheme { ... static function action_admin_enqueue_scripts() { wp_enqueue_script( 'ajax-recipes-hello-admin', get_stylesheet_directory_uri() . '/hello-admin.js', array( 'jquery' ), false, true ); } ... } Saturday, June 30, 2012
  • 20. Register a method to handle Ajax Dolly requests class AjaxRecipesTheme { static function load() { ... add_action( 'wp_ajax_hello_dolly', array( __CLASS__, 'action_wp_ajax_hello_dolly' ) ); } ... } Saturday, June 30, 2012
  • 21. Add the method to handle Ajax Dolly requests class AjaxRecipesTheme { ... static function action_wp_ajax_hello_dolly() { exit( hello_dolly_get_lyric() ); } ... } Saturday, June 30, 2012
  • 22. Ready to Serve! themes !"" index.php !"" recipes-child #   !"" hello-admin.js #   !"" functions.php #   $"" style.css !"" twentyeleven ... $"" twentyten Saturday, June 30, 2012
  • 23. And the back end looks... exactly the same as before but! and this is my but: Saturday, June 30, 2012
  • 24. What is it doing in there? Saturday, June 30, 2012
  • 25. Nice! But will Dolly be listening? In the back end? To that tiny but? Saturday, June 30, 2012
  • 26. Recipe: Hello Dolly, World! Ingredients: Ajax Hello Dolly A new page and template One more hook Saturday, June 30, 2012
  • 27. Prep Create a new page titled “Are You Dolly?” (we’ll assume it gets the default slug are-you-dolly) Saturday, June 30, 2012
  • 28. Mark It Up create theme file page-are-you-dolly.php: <?php get_header(); ?> <div id="primary"> <div id="content" role="main"> <h1 class="entry-title">Are You Dolly?</h1> <button id="ajax-recipe-impersonate-dolly">I'm Dolly</button> <p id="ajax-recipe-dolly-message"> If you're Dolly, I have a message for you. </p> </div><!-- #content --> </div><!-- #primary --> <?php get_footer(); ?> Saturday, June 30, 2012
  • 29. Inline JavaScript For now we’ll add a script to page-are-you-dolly.php: <script> jQuery( function( $ ) { var $message = $( '#ajax-recipe-dolly-message' ); $( '#ajax-recipe-impersonate-dolly' ).click( function() { $message.html( '...' ); $.ajax( { url: '<?php echo admin_url( 'admin-ajax.php' ); ?>', data: { action: 'hello_dolly' }, dataType: 'text', success: function( data ) { $message.html( data ); } } ); } ); } ); </script> <?php get_footer(); ?> Saturday, June 30, 2012
  • 30. Gimme jQuery On the front end, we have to ask for it As of WordPress 3.3, we can do this in page-are-you-dolly.php: <?php wp_enqueue_script( 'jquery' ); ?> <?php get_header() ?> ... Saturday, June 30, 2012
  • 31. Let the Front End In A different ajax action fires for non-logged-in users class AjaxRecipesTheme { static function load() { ... add_action( 'wp_ajax _nopriv _hello_dolly', array( __CLASS__, 'action_wp_ajax_hello_dolly' ) ); } ... } Saturday, June 30, 2012
  • 33. Refinement: Spider Garnish Ingredients: 1 spider template tweaks Saturday, June 30, 2012
  • 34. Spider (a.k.a. web spinner) Saturday, June 30, 2012
  • 35. Drop your spider in the theme themes !"" index.php !"" recipes-child #   !"" hello-admin.js #   !"" functions.php #   !"" spinner.gif #   $"" style.css !"" twentyeleven ... $"" twentyten Saturday, June 30, 2012
  • 36. Load the spider in page-are-you-dolly.php: <button id="ajax-recipe-impersonate-dolly">I'm Dolly</button> <p id="ajax-recipe-spinner" style="display:none;"> <img src="<?php echo get_stylesheet_directory_uri(); ?>/spinner.gif" alt="..." /> </p> <p id="ajax-recipe-dolly-message"> If you're Dolly, I have a message for you. </p> Saturday, June 30, 2012
  • 37. Show and hide the spider in page-are-you-dolly.php: var $message = $( '#ajax-recipe-dolly-message' ), $spinner = $( '#ajax-recipe-spinner' ); $( '#ajax-recipe-impersonate-dolly' ).click( function() { $message.hide(); $spinner.show(); $.ajax( { url: '<?php echo admin_url( 'admin-ajax.php' ); ?>', data: { action: 'hello_dolly' }, dataType: 'text', success: function( data ) { $spinner.hide(); $message.show().html( data ); } Saturday, June 30, 2012
  • 38. Onto Our Tuffet Saturday, June 30, 2012
  • 39. Recipe: Spider Ghoulash Ingredients: many spiders Saturday, June 30, 2012
  • 42. A Cry for Reason David DeSandro / Metafizzy creator of the ultra-cool isotope library pleads: “Isotope enables a wealth of functionality. But just because you can take advantage of its numerous features together, doesn’t mean you necessarily should. For each each feature you implement with Isotope, consider the benefit gained by users, at the cost of another level of complexity to your interface.” Saturday, June 30, 2012
  • 44. Programmer? Maybe ask the users. Users? Maybe show them the ghoulash. Everyone? Maybe AJAX ALL THE THINGS! Saturday, June 30, 2012
  • 45. Refinement: Script File Ingredients: a separate script file enqueueing server code configuration server code Saturday, June 30, 2012
  • 46. Cut the Inline Script Create a new theme file hello.js Copy the <script> contents in page-are-you-dolly.php Paste the code into hello.js Remove entire <script> from page-are-you-dolly.php page-are-you-dolly.php inline javascript hello.js Saturday, June 30, 2012
  • 47. themes !"" index.php !"" recipes-child #   !"" hello.js #   !"" hello-admin.js #   !"" functions.php #   !"" spinner.gif #   $"" style.css !"" twentyeleven ... $"" twentyten Saturday, June 30, 2012
  • 48. We’ll expand this call in page-are-you-dolly.php: <?php wp_enqueue_script( 'jquery' ); ?> to load both jQuery and our new hello script: <?php wp_enqueue_script( 'ajax-recipes-hello', get_stylesheet_directory_uri() . '/hello.js', array( 'jquery' ), false, true ); ?> Saturday, June 30, 2012
  • 49. Unmix It We need to get rid of the PHP code in hello.js: url: '<?php echo admin_url( 'admin-ajax.php' ); ?>', We can get that URL into a JavaScript variable (trust me): $.ajax( { url: ajaxRecipesConfig.ajaxurl, data: { action: 'hello_dolly' }, dataType: 'text', success: function( data ) { $spinner.hide(); $message.show().html( data ); } } ); Saturday, June 30, 2012
  • 50. Localize? Sort of. wp_localize_script() will create our variable for us. Back in page-are-you-dolly.php: wp_enqueue_script( 'ajax-recipes-hello', ... ); $hello_config = array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ); wp_localize_script( 'ajax-recipes-hello', 'ajaxRecipesConfig', $hello_config ); Saturday, June 30, 2012
  • 51. That’s It! Go forth and Ajax http://2012.reno.wordcamp.org/session/wordpress-ajax-recipes/ https://github.com/cyberhobo/wp-ajax-dolly-theme cyberhobo@cyberhobo.net Thanks! WordCamp Reno Tahoe 2012 Saturday, June 30, 2012