SlideShare una empresa de Scribd logo
1 de 22
Descargar para leer sin conexión
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

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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
 

Destacado (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
 

Similar a 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
 

Similar a 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
 

Último

Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 

Último (20)

"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 ...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
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
 
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...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
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
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
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...
 
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot ModelNavi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
Navi Mumbai Call Girls 🥰 8617370543 Service Offer VIP Hot Model
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 

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