SlideShare ist ein Scribd-Unternehmen logo
1 von 22
Downloaden Sie, um offline zu lesen
jQuery in Drupal:
overview, tools, how-tos
 DrupalCamp Vancouver 2008
Introduction

• jQuery is a JavaScript Framework

• In core since Drupal 5 (version 1.0.1)

• Modular, like Drupal itself

• and, like Drupal, constantly evolving...
Overview / Timeline
jQuery Syntax Refresher
• Selectors
   – $(‘#myId’), $(‘div.myClass’),
     $(‘li:not(.active)’), $(‘a[href^=“mailto”]’)
• Commands
   – .hide(), .show(), .slideToggle(), .each(), etc
• Utility Functions
   – $.each(), $.get(), $.browser(), $.noConflict()

• Chaining Example
  $('div.myClass').not(':first-child').hide().end().filter(':first-child').wrap
  ('<div class=quot;my-wrapperquot;></div>');
Important Functions

• drupal_add_js
  – Add a JavaScript file, setting or inline code to the
    page
  – parameters: data, type, scope, defer, cache
  – Examples:
     • drupal_add_js(drupal_get_path(‘module’,
       ‘mymodule’) .'/myjs.js');
     • drupal_add_js(array(‘myjs’=>$mysettings), ‘setting’);
     • Drupal_add_js(‘var myVar = “foo”;’, ‘inline’);
• Use ‘setting’ type to make your module’s
  settings available to js
Important Functions

• drupal_get_js()
  – called from phptemplate.engine (assigned
    to scripts variable)
  – makes a call to drupal_add_js() to get the
    $javascript array
  – $output .= '<script type=quot;text/javascriptquot;>
    Drupal.extend({ settings: '. drupal_to_js
    (call_user_func_array('array_merge_recursive',
    $data)) .quot; });</script>nquot;;
Important Functions

• drupal_to_js()
  – Converts a PHP variable into its JavaScript
    equivalent
  – e.g. convert a PHP array into a JSON object
  – used in the callback function for an AJAX
    path
The Drupal JavaScript Object

 drupal.js in D5:
 var Drupal = Drupal || {};



 drupal.js in D6:

 var Drupal = Drupal || { 'settings': {},
 'behaviors': {}, 'themes': {}, 'locale': {} };
Ajaxifying Drupal with jQuery

• Asynchronous JavaScript and XML
  – retrieve data from the server and load into
    the DOM of the current page without
    refreshing the page
  – $(‘#someDiv’).load(‘/serverResource’);
  – the above corresponds to about 20 lines of
    normal js
• jQuery provides different AJAX
  functions, depending on your needs
Ajaxifying Drupal with jQuery

• jQuery AJAX functions:
  – $(‘#someDiv’).load(url, parameters,
    callback);
  – $.get(url, parameters, callback)
  – $.post(url, parameters, callback)
  – $.ajax(options)
Ajaxifying Drupal with jQuery




                         11
Ajaxifying Drupal with jQuery

• Basic essentials:
  – $.get (or another AJAX method)
  – drupal/path (menu callback)
  – callback function
• drupal_to_js($var)
  – to convert your php array into a JSON
    array
• Drupal.parseJSON(data)
Ajaxifying Drupal with jQuery
                Menu Callback

$items[] = array(
  'path' => 'photostories/get/photos',
  'type' => MENU_CALLBACK,
  'access' => user_access('access content'),
  'callback' => 'kflick_get_photos_ajax'
);
Ajaxifying Drupal with jQuery
                Callback Function

function kflick_get_photos_ajax($nid) {
    $photo = kflick_get_photo($nid);
    $imagefile = theme('image', $photo);
    print drupal_to_js(array(
    'image' => $imagefile,
    )
    );
}
Ajaxifying Drupal with jQuery
Drupal.kflick = function() {
  var imageDetails = function(data) {
    var result = Drupal.parseJson(data);
    $('div.field-type-image div.field-item').html(result['image']);
  }
  $('a.kflick_button').click(function(){
    $('a.kflick_button').removeClass('active');
    $(this).addClass('active');
    $.get('/photostories/get/photos/'+ parseInt(this.id, 10), null,
imageDetails);
    return false;
  });
}

if (Drupal.jsEnabled) {
	

     $(document).ready(Drupal.kflick);
}
Drupal 6: behaviors

• In D6, wrap all your module’s jQuery
  behaviours in a function assigned to
  Drupal.behaviors.mymodule
• no need to call it within
  $(document).ready() as Drupal
  automatically does it for you
• all behaviors can then be reattached to
  DOM elements that have come from an
  AJAX call
Drupal 6: behaviors
Drupal.behaviors.kflick = function(context) {
  $('div.field-type-image:not(.kflick-processed)', context).addClass
(‘kflick-processed’).each(function(){
    var imageDetails = function(data) {
      var result = Drupal.parseJson(data);
      $('div.field-type-image div.field-item').html(result['image']);
    }
    $('a.kflick_button').click(function(){
      $('a.kflick_button').removeClass('active');
      $(this).addClass('active');
      $.get('/drupal/sandbox/photostories/get/photos/'+ parseInt
(this.id, 10), null, imageDetails);
      return false;
    });
  });
}
Drupal 6: behaviors
Drupal.attachBehaviors = function(context) {
  context = context || document;
  if (Drupal.jsEnabled) {
    // Execute all of them.
       jQuery.each(Drupal.behaviors,
   function() {
      this(context);
    });
  }
};
What is AHAH?

• Asynchronous HTML and HTTP
• still uses the XMLHttpRequest object
• still uses JavaScript
• loads html content retrieved from the
  server directly into the DOM - no
  parsing necessary
• AHAH in Drupal = AHAH Forms
• AHAH Forms Framework module
• In core as of D6
AHAH in Drupal 6
  $form['qt_wrapper']['tabs_more'] = array(
     '#type' => 'submit',
     '#value' => t('More tabs'),
     '#description' => t(quot;Click here to add more tabs.quot;),
     '#weight' => 1,
     '#submit' => array('qt_more_tabs_submit'), // If no
javascript action.
     '#ahah' => array(
        'path' => 'quicktabs/ahah',
        'wrapper' => 'quicktabs-tabs',
        'method' => 'replace',
        'effect' => 'fade',
     ),
  );
Drag & Drop
drupal_add_tabledrag($table_id, $action, $relationship, $group);

theme('table', $header, $rows, array('id' => 'my-table'));

$form['my_elements'][$delta]['weight']['#attributes']
['class'] = quot;my-elements-weightquot;;

$row = array(...);
$rows[] = array(
'data' => $row,
'class' => 'draggable',
);

drupal_add_tabledrag('my-module-table', 'order',
'sibling', 'my-elements-weight');
Resources

• JavaScript Startup Guide
  on api.drupal.org
• drupaldojo.com/lesson/ahah
• http://jquery.com
• Firebug console
• Books
  – Learning jQuery
  – jQuery in Action

Weitere ähnliche Inhalte

Was ist angesagt?

Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
Inbal Geffen
 
Drupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinDrupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton Shubkin
ADCI Solutions
 

Was ist angesagt? (20)

Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
Phase2 OpenPublish Presentation SF SemWeb Meetup, April 28, 2009
 
Geodaten & Drupal 7
Geodaten & Drupal 7Geodaten & Drupal 7
Geodaten & Drupal 7
 
Drupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton ShubkinDrupal 8: What's new? Anton Shubkin
Drupal 8: What's new? Anton Shubkin
 
Backbone js in drupal core
Backbone js in drupal coreBackbone js in drupal core
Backbone js in drupal core
 
PHPConf-TW 2012 # Twig
PHPConf-TW 2012 # TwigPHPConf-TW 2012 # Twig
PHPConf-TW 2012 # Twig
 
AngularJS Compile Process
AngularJS Compile ProcessAngularJS Compile Process
AngularJS Compile Process
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
AngularJS Services
AngularJS ServicesAngularJS Services
AngularJS Services
 
BackboneJs
BackboneJsBackboneJs
BackboneJs
 
jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)jQuery (DrupalCamp Toronto)
jQuery (DrupalCamp Toronto)
 
jQuery (MeshU)
jQuery (MeshU)jQuery (MeshU)
jQuery (MeshU)
 
AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
 
Convert modules from 6.x to 7.x
Convert modules from 6.x to 7.xConvert modules from 6.x to 7.x
Convert modules from 6.x to 7.x
 
Jquery presentation
Jquery presentationJquery presentation
Jquery presentation
 
JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)JavaScript Libraries (Kings of Code)
JavaScript Libraries (Kings of Code)
 
Hack tutorial
Hack tutorialHack tutorial
Hack tutorial
 
JavaScript Libraries (@Media)
JavaScript Libraries (@Media)JavaScript Libraries (@Media)
JavaScript Libraries (@Media)
 
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
Dicoding Developer Coaching #27: Android | Membuat Aplikasi Support Online Ma...
 
AngularJS first steps
AngularJS first stepsAngularJS first steps
AngularJS first steps
 

Andere mochten auch (8)

Prototype & jQuery
Prototype & jQueryPrototype & jQuery
Prototype & jQuery
 
jQuery Presentation
jQuery PresentationjQuery Presentation
jQuery Presentation
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginning
 
jQuery in 15 minutes
jQuery in 15 minutesjQuery in 15 minutes
jQuery in 15 minutes
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
jQuery for beginners
jQuery for beginnersjQuery for beginners
jQuery for beginners
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
jQuery Essentials
jQuery EssentialsjQuery Essentials
jQuery Essentials
 

Ähnlich wie JQuery In Drupal

Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
Aaronius
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
Inbal Geffen
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
Jarod Ferguson
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
LEDC 2016
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuery
deimos
 
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
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Tree
adamlogic
 

Ähnlich wie JQuery In Drupal (20)

Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
DOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQueryDOM Scripting Toolkit - jQuery
DOM Scripting Toolkit - jQuery
 
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 JavascriptjQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
jQuery UI Widgets, Drag and Drop, Drupal 7 Javascript
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016
 
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
 
Jqeury ajax plugins
Jqeury ajax pluginsJqeury ajax plugins
Jqeury ajax plugins
 
Taming that client side mess with Backbone.js
Taming that client side mess with Backbone.jsTaming that client side mess with Backbone.js
Taming that client side mess with Backbone.js
 
Asynchronous Interfaces
Asynchronous InterfacesAsynchronous Interfaces
Asynchronous Interfaces
 
Virtual Madness @ Etsy
Virtual Madness @ EtsyVirtual Madness @ Etsy
Virtual Madness @ Etsy
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Анатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to zАнатолий Поляков - Drupal.ajax framework from a to z
Анатолий Поляков - Drupal.ajax framework from a to z
 
[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC[Coscup 2012] JavascriptMVC
[Coscup 2012] JavascriptMVC
 
Remy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQueryRemy Sharp The DOM scripting toolkit jQuery
Remy Sharp The DOM scripting toolkit jQuery
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
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)
 
jQuery (BostonPHP)
jQuery (BostonPHP)jQuery (BostonPHP)
jQuery (BostonPHP)
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Tree
 

Kürzlich hochgeladen

Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Ransomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdfRansomware_Q4_2023. The report. [EN].pdf
Ransomware_Q4_2023. The report. [EN].pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 

JQuery In Drupal

  • 1. jQuery in Drupal: overview, tools, how-tos DrupalCamp Vancouver 2008
  • 2. Introduction • jQuery is a JavaScript Framework • In core since Drupal 5 (version 1.0.1) • Modular, like Drupal itself • and, like Drupal, constantly evolving...
  • 4. jQuery Syntax Refresher • Selectors – $(‘#myId’), $(‘div.myClass’), $(‘li:not(.active)’), $(‘a[href^=“mailto”]’) • Commands – .hide(), .show(), .slideToggle(), .each(), etc • Utility Functions – $.each(), $.get(), $.browser(), $.noConflict() • Chaining Example $('div.myClass').not(':first-child').hide().end().filter(':first-child').wrap ('<div class=quot;my-wrapperquot;></div>');
  • 5. Important Functions • drupal_add_js – Add a JavaScript file, setting or inline code to the page – parameters: data, type, scope, defer, cache – Examples: • drupal_add_js(drupal_get_path(‘module’, ‘mymodule’) .'/myjs.js'); • drupal_add_js(array(‘myjs’=>$mysettings), ‘setting’); • Drupal_add_js(‘var myVar = “foo”;’, ‘inline’); • Use ‘setting’ type to make your module’s settings available to js
  • 6. Important Functions • drupal_get_js() – called from phptemplate.engine (assigned to scripts variable) – makes a call to drupal_add_js() to get the $javascript array – $output .= '<script type=quot;text/javascriptquot;> Drupal.extend({ settings: '. drupal_to_js (call_user_func_array('array_merge_recursive', $data)) .quot; });</script>nquot;;
  • 7. Important Functions • drupal_to_js() – Converts a PHP variable into its JavaScript equivalent – e.g. convert a PHP array into a JSON object – used in the callback function for an AJAX path
  • 8. The Drupal JavaScript Object drupal.js in D5: var Drupal = Drupal || {}; drupal.js in D6: var Drupal = Drupal || { 'settings': {}, 'behaviors': {}, 'themes': {}, 'locale': {} };
  • 9. Ajaxifying Drupal with jQuery • Asynchronous JavaScript and XML – retrieve data from the server and load into the DOM of the current page without refreshing the page – $(‘#someDiv’).load(‘/serverResource’); – the above corresponds to about 20 lines of normal js • jQuery provides different AJAX functions, depending on your needs
  • 10. Ajaxifying Drupal with jQuery • jQuery AJAX functions: – $(‘#someDiv’).load(url, parameters, callback); – $.get(url, parameters, callback) – $.post(url, parameters, callback) – $.ajax(options)
  • 12. Ajaxifying Drupal with jQuery • Basic essentials: – $.get (or another AJAX method) – drupal/path (menu callback) – callback function • drupal_to_js($var) – to convert your php array into a JSON array • Drupal.parseJSON(data)
  • 13. Ajaxifying Drupal with jQuery Menu Callback $items[] = array( 'path' => 'photostories/get/photos', 'type' => MENU_CALLBACK, 'access' => user_access('access content'), 'callback' => 'kflick_get_photos_ajax' );
  • 14. Ajaxifying Drupal with jQuery Callback Function function kflick_get_photos_ajax($nid) { $photo = kflick_get_photo($nid); $imagefile = theme('image', $photo); print drupal_to_js(array( 'image' => $imagefile, ) ); }
  • 15. Ajaxifying Drupal with jQuery Drupal.kflick = function() { var imageDetails = function(data) { var result = Drupal.parseJson(data); $('div.field-type-image div.field-item').html(result['image']); } $('a.kflick_button').click(function(){ $('a.kflick_button').removeClass('active'); $(this).addClass('active'); $.get('/photostories/get/photos/'+ parseInt(this.id, 10), null, imageDetails); return false; }); } if (Drupal.jsEnabled) { $(document).ready(Drupal.kflick); }
  • 16. Drupal 6: behaviors • In D6, wrap all your module’s jQuery behaviours in a function assigned to Drupal.behaviors.mymodule • no need to call it within $(document).ready() as Drupal automatically does it for you • all behaviors can then be reattached to DOM elements that have come from an AJAX call
  • 17. Drupal 6: behaviors Drupal.behaviors.kflick = function(context) { $('div.field-type-image:not(.kflick-processed)', context).addClass (‘kflick-processed’).each(function(){ var imageDetails = function(data) { var result = Drupal.parseJson(data); $('div.field-type-image div.field-item').html(result['image']); } $('a.kflick_button').click(function(){ $('a.kflick_button').removeClass('active'); $(this).addClass('active'); $.get('/drupal/sandbox/photostories/get/photos/'+ parseInt (this.id, 10), null, imageDetails); return false; }); }); }
  • 18. Drupal 6: behaviors Drupal.attachBehaviors = function(context) { context = context || document; if (Drupal.jsEnabled) { // Execute all of them. jQuery.each(Drupal.behaviors, function() { this(context); }); } };
  • 19. What is AHAH? • Asynchronous HTML and HTTP • still uses the XMLHttpRequest object • still uses JavaScript • loads html content retrieved from the server directly into the DOM - no parsing necessary • AHAH in Drupal = AHAH Forms • AHAH Forms Framework module • In core as of D6
  • 20. AHAH in Drupal 6 $form['qt_wrapper']['tabs_more'] = array( '#type' => 'submit', '#value' => t('More tabs'), '#description' => t(quot;Click here to add more tabs.quot;), '#weight' => 1, '#submit' => array('qt_more_tabs_submit'), // If no javascript action. '#ahah' => array( 'path' => 'quicktabs/ahah', 'wrapper' => 'quicktabs-tabs', 'method' => 'replace', 'effect' => 'fade', ), );
  • 21. Drag & Drop drupal_add_tabledrag($table_id, $action, $relationship, $group); theme('table', $header, $rows, array('id' => 'my-table')); $form['my_elements'][$delta]['weight']['#attributes'] ['class'] = quot;my-elements-weightquot;; $row = array(...); $rows[] = array( 'data' => $row, 'class' => 'draggable', ); drupal_add_tabledrag('my-module-table', 'order', 'sibling', 'my-elements-weight');
  • 22. Resources • JavaScript Startup Guide on api.drupal.org • drupaldojo.com/lesson/ahah • http://jquery.com • Firebug console • Books – Learning jQuery – jQuery in Action