SlideShare a Scribd company logo
1 of 26
Download to read offline
AJAX on Drupal the right way
Nicolás Bouhid
Software Architect
CI&T
About me
● Born in Buenos Aires, Argentina
● PHP developer since 2008
● Drupalist since 2011
● Lives in Brazil since 2013
● Works at
● Drupal contributions:
○ PDF Export
○ Deploy overview views
Linkedin
http://linkedin.com/in/nicolasbouhid/en
D.o. profile
https://www.drupal.org/u/nbouhid
Agenda
● What is Ajax API?
● jQuery.ajax vs Ajax API
● How it works?
● Ajax Commands
● Drupal.behaviors
● Form API + Ajax API
● How to use it without a form
● What’s new on Drupal 8?
What is Ajax API?
Drupal's Ajax framework is used to dynamically
update parts of a page's HTML based on data
from the server. Upon a specified event, such as a
button click, a callback function is triggered which
performs server-side logic and may return updated
markup, which is then replaced on-the-fly with no page
refresh necessary.
What is Ajax API?
This framework creates a PHP macro language
that allows the server to instruct JavaScript to
perform actions on the client browser.
These instructions are called commands.
What is Ajax API?
This means…
● ...you can include or reload content on your page...
● …init libraries or execute jQuery functions...
● …you can load CSS/JS libraries exactly when it’s necessary...
… from server side, and everything with almost no custom JS code!
jQuery.ajax vs Ajax API
jQuery.ajax is simply a cross browser implementation
to make XMLHttpRequests
Ajax API is built on jQuery and it is a complete framework
designed for Drupal with three main benefits:
● Updates your Drupal.settings object
● Keeps the ids on the DOM unique
● Loads CSS/JS files asynchronously (once!)
That is what makes it so powerful and usually a wise choice
How it works?
1. XMLHttpRequest
2.$com
m
ands[]
3.JS
functions
Default Ajax API
Delivery
callback
drupal_deliver_html_page() ajax_deliver()
Ajax
Framework
Ajax Commands
They are client side instructions controlled by server side
// $(‘#content’).hide();
$commands[] = ajax_command_invoke('#content', 'hide');
// $(‘#content’).html(‘DrupalCamp’);
$commands[] = ajax_command_html('#content', 'DrupalCamp’);
// $(‘#content’).fadeIn(‘fast’);
$commands[] = ajax_command_invoke('#content', 'fadeIn', array('fast'));
Ajax Commands
This means more reusability and covers most of
the important operations that are usually required
on AJAX requests!
Do you not find what you need on the core ajax commands?
Really??? Ok, no problem, you can create your own :)
PSST, wanna see more? Check misc/ajax.js
Ajax Commands
All ajax commands are defined in the following JS object
Drupal.ajax.prototype.commands
This means that… you can create your own!
Drupal.ajax.prototype.commands.helloWorld = function (ajax, response, status) {
alert('hello world!');
}
Drupal.behaviors
The official Drupal documentation says that every module
that implements JS actions, needs to attach its logic to
Drupal.behaviors:
Drupal.behaviors.exampleModule = {
attach: function (context, settings) {
$('.example', context).click(function () {
$(this).next('ul').toggle('show');
});
}
};
Drupal.behaviors
When is it executed?
● $(document).ready()
● After an overlay is opened
● Every time new content is included in the DOM using Ajax API
Views, CTools, Media, Panels, Authcache, and many other modules uses it.
So if you use any of these modules and you can’t make your JS execute at
the right moment, then you should give it a try ;)
Drupal.behaviors
But wait… There is a catch!
If you don’t use it properly…
You could have more
problems than solutions!
Let’s take a look at that example code again..
Drupal.behaviors.exampleModule = {
attach: function (context, settings) {
$('.example', context).click(function () {
$(this).next('ul').toggle('show');
});
}
};
Make sure your code runs only when necessary!
Drupal.behaviors
Form API + Ajax API
You can use Ajax API combined with Form API
On most cases, it used to reload fields or load new
HTML on the page
Let’s see an example (from ajax_example.module)
Form API + Ajax API
/**
* A very basic form which with an AJAX-enabled submit.
*/
function ajax_example_submit_driven_ajax($form, &$form_state) {
$form['box'] = array(
'#type' => 'markup',
'#prefix' => '<div id="box">',
'#suffix' => '</div>',
'#markup' => '<h1>Initial markup for box</h1>',
);
$form['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
'callback' => 'ajax_example_submit_driven_callback',
'wrapper' => 'box',
'effect' => 'none',
'progress' => array('type' => 'throbber'),
),
'#value' => t('Submit'),
);
return $form;
}
Form API + Ajax API
/**
* Callback for submit_driven example.
*
* Select the 'box' element, change the markup in it, and return it as a
* renderable array.
*/
function ajax_example_submit_driven_callback($form, $form_state) {
$element = $form['box'];
$element['#markup'] = "Clicked submit ({$form_state['values']['op']}): " . date('c');
return $element;
}
Form API + Ajax API
$form['submit'] = array(
'#type' => 'submit',
'#ajax' => array(
'callback' => 'ajax_example_commands_callback',
),
'#value' => t('Submit'),
);
function ajax_example_commands_callback($form, $form_state) {
$commands = array();
$new_string = "Clicked submit ({$form_state['values']['op']}): " . date('c');
$commands[] = ajax_command_replace('#box', $new_string);
$commands[] = ajax_command_alert(t('Updated!'));
return array('#type' => 'ajax', '#commands' => $commands);
}
Form API + Ajax API
It uses the jQuery Form plugin to make Ajax POST requests
that provides the following events:
● beforeSerialize
Runs before field data is collected.
● beforeSubmit
Modify form values prior to form submission.
● beforeSend
Prepare the Ajax request before it is sent.
● success
● error
Form API + Ajax API
You can extend or override events safely!
var defaultBeforeSubmit = Drupal.ajax.prototype.beforeSubmit;
Drupal.ajax['#my-submit'].beforeSubmit = function (form_values, element, options) {
executeMyStuff(form_values, element);
// Remove this line to override the default functionality.
return defaultBeforeSubmit(form_values, element, options);
};
How to use it without a form
What happens if I don’t have a form?
Don’t worry, there is a way :)
You can use a link
drupal_add_library('system', 'drupal.ajax');
$link = l(t('Click here'), 'my/ajax/url/nojs', array(
'attributes' => array(
'class' => array('use-ajax'),
),
));
And on you page callback of the path my/ajax/url, you just need to:
$output = t("This is some content delivered via AJAX");
$commands = array();
$commands[] = ajax_command_append('#myDiv', $output);
return array(
'#type' => 'ajax',
'#commands' => $commands,
);
How to use it without a form
Remember to set
ajax_deliver as the
delivery callback on
your menu item
definition!
How to use it without a form
You can also instantiate your own Drupal.ajax object
var base = $(this).attr('id');
var elementSettings = {
url: settings.basePath + settings.pathPrefix + 'my/ajax/url/nojs',
event: 'click',
progress: {
type: 'throbber'
}
};
Drupal.ajax[base] = new Drupal.ajax(base, this, elementSettings);
$(this).click();
What’s new on Drupal 8?
● Commands are built using classes and they may have
assets/dependencies attached to it
● Code cleanup
● Documentation is so much better
● New command: redirect
● More flexibility when passing parameters from server side so it’s
easier to instantiate your plugins!
That was it!

More Related Content

What's hot

Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJSWei Ru
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - IntroductionSagar Acharya
 
The Chaos Tools Suite
The Chaos Tools SuiteThe Chaos Tools Suite
The Chaos Tools Suitemerlinofchaos
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPressCaldera Labs
 
Backbone.js and friends
Backbone.js and friendsBackbone.js and friends
Backbone.js and friendsGood Robot
 
Building a dashboard using AngularJS
Building a dashboard using AngularJSBuilding a dashboard using AngularJS
Building a dashboard using AngularJSRajthilakMCA
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework Sakthi Bro
 
Leveraging the Chaos tool suite for module development
Leveraging the Chaos tool suite  for module developmentLeveraging the Chaos tool suite  for module development
Leveraging the Chaos tool suite for module developmentzroger
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS ArchitectureEyal Vardi
 
AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014Dariusz Kalbarczyk
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IVisual Engineering
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsEPAM Systems
 
Intro to Rails Give Camp Atlanta
Intro to Rails Give Camp AtlantaIntro to Rails Give Camp Atlanta
Intro to Rails Give Camp AtlantaJason Noble
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing optionsNir Kaufman
 

What's hot (20)

Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - Introduction
 
The Chaos Tools Suite
The Chaos Tools SuiteThe Chaos Tools Suite
The Chaos Tools Suite
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPress
 
Backbone.js and friends
Backbone.js and friendsBackbone.js and friends
Backbone.js and friends
 
Introduction to AngularJS
Introduction to AngularJSIntroduction to AngularJS
Introduction to AngularJS
 
Building a dashboard using AngularJS
Building a dashboard using AngularJSBuilding a dashboard using AngularJS
Building a dashboard using AngularJS
 
Why angular js Framework
Why angular js Framework Why angular js Framework
Why angular js Framework
 
Leveraging the Chaos tool suite for module development
Leveraging the Chaos tool suite  for module developmentLeveraging the Chaos tool suite  for module development
Leveraging the Chaos tool suite for module development
 
Angular js
Angular jsAngular js
Angular js
 
AngularJS Basics with Example
AngularJS Basics with ExampleAngularJS Basics with Example
AngularJS Basics with Example
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014AngularJS Mobile Warsaw 20-10-2014
AngularJS Mobile Warsaw 20-10-2014
 
Angularjs Basics
Angularjs BasicsAngularjs Basics
Angularjs Basics
 
Workshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte IWorkshop 12: AngularJS Parte I
Workshop 12: AngularJS Parte I
 
Jquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript BasicsJquery Complete Presentation along with Javascript Basics
Jquery Complete Presentation along with Javascript Basics
 
Intro to Rails Give Camp Atlanta
Intro to Rails Give Camp AtlantaIntro to Rails Give Camp Atlanta
Intro to Rails Give Camp Atlanta
 
Catalog display
Catalog displayCatalog display
Catalog display
 
Angular js routing options
Angular js routing optionsAngular js routing options
Angular js routing options
 

Viewers also liked

MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 Joe Ferguson
 
Laravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routingLaravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routingChristopher Pecoraro
 
jQuery from the very beginning
jQuery from the very beginningjQuery from the very beginning
jQuery from the very beginningAnis Ahmad
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slidesSmithss25
 
Ajax Union 2017 Capabilities Deck - B2B Digital Marketing ABM
Ajax Union 2017 Capabilities Deck - B2B Digital Marketing ABMAjax Union 2017 Capabilities Deck - B2B Digital Marketing ABM
Ajax Union 2017 Capabilities Deck - B2B Digital Marketing ABMJoe Apfelbaum
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksSlideShare
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShareSlideShare
 

Viewers also liked (10)

Introduction to j_query
Introduction to j_queryIntroduction to j_query
Introduction to j_query
 
MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5 MidwestPHP 2016 - Adventures in Laravel 5
MidwestPHP 2016 - Adventures in Laravel 5
 
Laravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routingLaravel 5 Annotations: RESTful API routing
Laravel 5 Annotations: RESTful API routing
 
Bootstrap
BootstrapBootstrap
Bootstrap
 
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
 
Ajax ppt - 32 slides
Ajax ppt - 32 slidesAjax ppt - 32 slides
Ajax ppt - 32 slides
 
Ajax Union 2017 Capabilities Deck - B2B Digital Marketing ABM
Ajax Union 2017 Capabilities Deck - B2B Digital Marketing ABMAjax Union 2017 Capabilities Deck - B2B Digital Marketing ABM
Ajax Union 2017 Capabilities Deck - B2B Digital Marketing ABM
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Similar to Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016

Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)Igor Bronovskyy
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersCaldera Labs
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupalkatbailey
 
Анатолий Поляков - 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 zLEDC 2016
 
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
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...LEDC 2016
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindValentine Matsveiko
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery ApplicationsRebecca Murphey
 
Demystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsDemystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsMichael Miles
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to DjangoJoaquim Rocha
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...Fabio Franzini
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's CodeWildan Maulana
 
NYCCAMP 2015 Demystifying Drupal AJAX Callback Commands
NYCCAMP 2015 Demystifying Drupal AJAX Callback CommandsNYCCAMP 2015 Demystifying Drupal AJAX Callback Commands
NYCCAMP 2015 Demystifying Drupal AJAX Callback CommandsMichael Miles
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenerytoddbr
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'sAntônio Roberto Silva
 

Similar to Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016 (20)

Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
09 - express nodes on the right angle - vitaliy basyuk - it event 2013 (5)
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupal
 
Анатолий Поляков - 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
 
Angular js
Angular jsAngular js
Angular js
 
Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
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)
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
Валентин Мацвейко та Владислав Мойсеєнко — D8: Migrate Yourself: code->module...
 
Migrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mindMigrate yourself. code -> module -> mind
Migrate yourself. code -> module -> mind
 
Building Large jQuery Applications
Building Large jQuery ApplicationsBuilding Large jQuery Applications
Building Large jQuery Applications
 
Demystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback CommandsDemystifying Drupal AJAX Callback Commands
Demystifying Drupal AJAX Callback Commands
 
Introduction to Django
Introduction to DjangoIntroduction to Django
Introduction to Django
 
WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...WebNet Conference 2012 - Designing complex applications using html5 and knock...
WebNet Conference 2012 - Designing complex applications using html5 and knock...
 
Exploring Symfony's Code
Exploring Symfony's CodeExploring Symfony's Code
Exploring Symfony's Code
 
NYCCAMP 2015 Demystifying Drupal AJAX Callback Commands
NYCCAMP 2015 Demystifying Drupal AJAX Callback CommandsNYCCAMP 2015 Demystifying Drupal AJAX Callback Commands
NYCCAMP 2015 Demystifying Drupal AJAX Callback Commands
 
Javascript first-class citizenery
Javascript first-class citizeneryJavascript first-class citizenery
Javascript first-class citizenery
 
using Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API'susing Mithril.js + postgREST to build and consume API's
using Mithril.js + postgREST to build and consume API's
 

Recently uploaded

Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMartaLoveguard
 
NSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationNSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationMarko4394
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作ys8omjxb
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Excelmac1
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一z xss
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书zdzoqco
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationLinaWolf1
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa494f574xmv
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxDyna Gilbert
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhimiss dipika
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一Fs
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Paul Calvano
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书rnrncn29
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书rnrncn29
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITMgdsc13
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleanscorenetworkseo
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predieusebiomeyer
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxeditsforyah
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)Christopher H Felton
 

Recently uploaded (20)

Magic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptxMagic exist by Marta Loveguard - presentation.pptx
Magic exist by Marta Loveguard - presentation.pptx
 
NSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentationNSX-T and Service Interfaces presentation
NSX-T and Service Interfaces presentation
 
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
Potsdam FH学位证,波茨坦应用技术大学毕业证书1:1制作
 
Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...Blepharitis inflammation of eyelid symptoms cause everything included along w...
Blepharitis inflammation of eyelid symptoms cause everything included along w...
 
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
办理(UofR毕业证书)罗切斯特大学毕业证成绩单原版一比一
 
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
办理多伦多大学毕业证成绩单|购买加拿大UTSG文凭证书
 
PHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 DocumentationPHP-based rendering of TYPO3 Documentation
PHP-based rendering of TYPO3 Documentation
 
Film cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasaFilm cover research (1).pptxsdasdasdasdasdasa
Film cover research (1).pptxsdasdasdasdasdasa
 
Top 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptxTop 10 Interactive Website Design Trends in 2024.pptx
Top 10 Interactive Website Design Trends in 2024.pptx
 
Contact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New DelhiContact Rya Baby for Call Girls New Delhi
Contact Rya Baby for Call Girls New Delhi
 
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
定制(AUT毕业证书)新西兰奥克兰理工大学毕业证成绩单原版一比一
 
Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24Font Performance - NYC WebPerf Meetup April '24
Font Performance - NYC WebPerf Meetup April '24
 
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
『澳洲文凭』买拉筹伯大学毕业证书成绩单办理澳洲LTU文凭学位证书
 
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
『澳洲文凭』买詹姆士库克大学毕业证书成绩单办理澳洲JCU文凭学位证书
 
Git and Github workshop GDSC MLRITM
Git and Github  workshop GDSC MLRITMGit and Github  workshop GDSC MLRITM
Git and Github workshop GDSC MLRITM
 
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in  Rk Puram 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Rk Puram 🔝 9953056974 🔝 Delhi escort Service
 
Elevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New OrleansElevate Your Business with Our IT Expertise in New Orleans
Elevate Your Business with Our IT Expertise in New Orleans
 
SCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is prediSCM Symposium PPT Format Customer loyalty is predi
SCM Symposium PPT Format Customer loyalty is predi
 
Q4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptxQ4-1-Illustrating-Hypothesis-Testing.pptx
Q4-1-Illustrating-Hypothesis-Testing.pptx
 
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
A Good Girl's Guide to Murder (A Good Girl's Guide to Murder, #1)
 

Ajax on drupal the right way - DrupalCamp Campinas, São Paulo, Brazil 2016

  • 1. AJAX on Drupal the right way Nicolás Bouhid Software Architect CI&T
  • 2. About me ● Born in Buenos Aires, Argentina ● PHP developer since 2008 ● Drupalist since 2011 ● Lives in Brazil since 2013 ● Works at ● Drupal contributions: ○ PDF Export ○ Deploy overview views Linkedin http://linkedin.com/in/nicolasbouhid/en D.o. profile https://www.drupal.org/u/nbouhid
  • 3. Agenda ● What is Ajax API? ● jQuery.ajax vs Ajax API ● How it works? ● Ajax Commands ● Drupal.behaviors ● Form API + Ajax API ● How to use it without a form ● What’s new on Drupal 8?
  • 4. What is Ajax API? Drupal's Ajax framework is used to dynamically update parts of a page's HTML based on data from the server. Upon a specified event, such as a button click, a callback function is triggered which performs server-side logic and may return updated markup, which is then replaced on-the-fly with no page refresh necessary.
  • 5. What is Ajax API? This framework creates a PHP macro language that allows the server to instruct JavaScript to perform actions on the client browser. These instructions are called commands.
  • 6. What is Ajax API? This means… ● ...you can include or reload content on your page... ● …init libraries or execute jQuery functions... ● …you can load CSS/JS libraries exactly when it’s necessary... … from server side, and everything with almost no custom JS code!
  • 7. jQuery.ajax vs Ajax API jQuery.ajax is simply a cross browser implementation to make XMLHttpRequests Ajax API is built on jQuery and it is a complete framework designed for Drupal with three main benefits: ● Updates your Drupal.settings object ● Keeps the ids on the DOM unique ● Loads CSS/JS files asynchronously (once!) That is what makes it so powerful and usually a wise choice
  • 8. How it works? 1. XMLHttpRequest 2.$com m ands[] 3.JS functions Default Ajax API Delivery callback drupal_deliver_html_page() ajax_deliver() Ajax Framework
  • 9. Ajax Commands They are client side instructions controlled by server side // $(‘#content’).hide(); $commands[] = ajax_command_invoke('#content', 'hide'); // $(‘#content’).html(‘DrupalCamp’); $commands[] = ajax_command_html('#content', 'DrupalCamp’); // $(‘#content’).fadeIn(‘fast’); $commands[] = ajax_command_invoke('#content', 'fadeIn', array('fast'));
  • 10. Ajax Commands This means more reusability and covers most of the important operations that are usually required on AJAX requests! Do you not find what you need on the core ajax commands? Really??? Ok, no problem, you can create your own :) PSST, wanna see more? Check misc/ajax.js
  • 11. Ajax Commands All ajax commands are defined in the following JS object Drupal.ajax.prototype.commands This means that… you can create your own! Drupal.ajax.prototype.commands.helloWorld = function (ajax, response, status) { alert('hello world!'); }
  • 12. Drupal.behaviors The official Drupal documentation says that every module that implements JS actions, needs to attach its logic to Drupal.behaviors: Drupal.behaviors.exampleModule = { attach: function (context, settings) { $('.example', context).click(function () { $(this).next('ul').toggle('show'); }); } };
  • 13. Drupal.behaviors When is it executed? ● $(document).ready() ● After an overlay is opened ● Every time new content is included in the DOM using Ajax API Views, CTools, Media, Panels, Authcache, and many other modules uses it. So if you use any of these modules and you can’t make your JS execute at the right moment, then you should give it a try ;)
  • 14. Drupal.behaviors But wait… There is a catch! If you don’t use it properly… You could have more problems than solutions!
  • 15. Let’s take a look at that example code again.. Drupal.behaviors.exampleModule = { attach: function (context, settings) { $('.example', context).click(function () { $(this).next('ul').toggle('show'); }); } }; Make sure your code runs only when necessary! Drupal.behaviors
  • 16. Form API + Ajax API You can use Ajax API combined with Form API On most cases, it used to reload fields or load new HTML on the page Let’s see an example (from ajax_example.module)
  • 17. Form API + Ajax API /** * A very basic form which with an AJAX-enabled submit. */ function ajax_example_submit_driven_ajax($form, &$form_state) { $form['box'] = array( '#type' => 'markup', '#prefix' => '<div id="box">', '#suffix' => '</div>', '#markup' => '<h1>Initial markup for box</h1>', ); $form['submit'] = array( '#type' => 'submit', '#ajax' => array( 'callback' => 'ajax_example_submit_driven_callback', 'wrapper' => 'box', 'effect' => 'none', 'progress' => array('type' => 'throbber'), ), '#value' => t('Submit'), ); return $form; }
  • 18. Form API + Ajax API /** * Callback for submit_driven example. * * Select the 'box' element, change the markup in it, and return it as a * renderable array. */ function ajax_example_submit_driven_callback($form, $form_state) { $element = $form['box']; $element['#markup'] = "Clicked submit ({$form_state['values']['op']}): " . date('c'); return $element; }
  • 19. Form API + Ajax API $form['submit'] = array( '#type' => 'submit', '#ajax' => array( 'callback' => 'ajax_example_commands_callback', ), '#value' => t('Submit'), ); function ajax_example_commands_callback($form, $form_state) { $commands = array(); $new_string = "Clicked submit ({$form_state['values']['op']}): " . date('c'); $commands[] = ajax_command_replace('#box', $new_string); $commands[] = ajax_command_alert(t('Updated!')); return array('#type' => 'ajax', '#commands' => $commands); }
  • 20. Form API + Ajax API It uses the jQuery Form plugin to make Ajax POST requests that provides the following events: ● beforeSerialize Runs before field data is collected. ● beforeSubmit Modify form values prior to form submission. ● beforeSend Prepare the Ajax request before it is sent. ● success ● error
  • 21. Form API + Ajax API You can extend or override events safely! var defaultBeforeSubmit = Drupal.ajax.prototype.beforeSubmit; Drupal.ajax['#my-submit'].beforeSubmit = function (form_values, element, options) { executeMyStuff(form_values, element); // Remove this line to override the default functionality. return defaultBeforeSubmit(form_values, element, options); };
  • 22. How to use it without a form What happens if I don’t have a form? Don’t worry, there is a way :)
  • 23. You can use a link drupal_add_library('system', 'drupal.ajax'); $link = l(t('Click here'), 'my/ajax/url/nojs', array( 'attributes' => array( 'class' => array('use-ajax'), ), )); And on you page callback of the path my/ajax/url, you just need to: $output = t("This is some content delivered via AJAX"); $commands = array(); $commands[] = ajax_command_append('#myDiv', $output); return array( '#type' => 'ajax', '#commands' => $commands, ); How to use it without a form Remember to set ajax_deliver as the delivery callback on your menu item definition!
  • 24. How to use it without a form You can also instantiate your own Drupal.ajax object var base = $(this).attr('id'); var elementSettings = { url: settings.basePath + settings.pathPrefix + 'my/ajax/url/nojs', event: 'click', progress: { type: 'throbber' } }; Drupal.ajax[base] = new Drupal.ajax(base, this, elementSettings); $(this).click();
  • 25. What’s new on Drupal 8? ● Commands are built using classes and they may have assets/dependencies attached to it ● Code cleanup ● Documentation is so much better ● New command: redirect ● More flexibility when passing parameters from server side so it’s easier to instantiate your plugins!