SlideShare une entreprise Scribd logo
1  sur  128
Ajax
The quest to turn Web applications
into desktop applications
What is Ajax?
It’s hard to avoid hearing about Ajax in Web
discussions these days, but what is it really?
What’s in a Name?
What’s in a Name?

The term originally stood for “Asynchronous JavaScript
and XML”
What’s in a Name?

The term originally stood for “Asynchronous JavaScript
and XML”
  But it doesn’t have to be asynchronous
What’s in a Name?

The term originally stood for “Asynchronous JavaScript
and XML”
  But it doesn’t have to be asynchronous
  Or involve XML
What’s in a Name?

The term originally stood for “Asynchronous JavaScript
and XML”
  But it doesn’t have to be asynchronous
  Or involve XML
Nowadays the term pretty much stands on its own
The Accidental Feature
The Accidental Feature
It’s hard to change the Web
The Accidental Feature
It’s hard to change the Web
  You need to get through standards committees
The Accidental Feature
It’s hard to change the Web
  You need to get through standards committees
  And it doesn’t really count until most browsers agree
The Accidental Feature
It’s hard to change the Web
  You need to get through standards committees
  And it doesn’t really count until most browsers agree
In 1999 Microsoft added an XMLHTTP ActiveX control
The Accidental Feature
It’s hard to change the Web
  You need to get through standards committees
  And it doesn’t really count until most browsers agree
In 1999 Microsoft added an XMLHTTP ActiveX control
  Not to be outdone, Mozilla, Safari, and Opera copied
  it, adding native XMLHttpRequest objects
The Accidental Feature
It’s hard to change the Web
  You need to get through standards committees
  And it doesn’t really count until most browsers agree
In 1999 Microsoft added an XMLHTTP ActiveX control
  Not to be outdone, Mozilla, Safari, and Opera copied
  it, adding native XMLHttpRequest objects
  No one really knew what to do with it
Someone Figured it Out!
Someone Figured it Out!
Google figured out the
browsers had all
learned a new trick
Someone Figured it Out!
Google figured out the
browsers had all
learned a new trick
They put it to use
Someone Figured it Out!
Google figured out the
browsers had all
learned a new trick
They put it to use
  Gmail, 2004
Someone Figured it Out!
Google figured out the
browsers had all
learned a new trick
They put it to use
  Gmail, 2004
  Google Maps, 2005
Someone Figured it Out!
Google figured out the
browsers had all
learned a new trick
They put it to use
  Gmail, 2004
  Google Maps, 2005
Ajax was born
Why the History Lesson?
Why the History Lesson?
Ajax was never really planned
Why the History Lesson?
Ajax was never really planned
  Even today, the way it is used are is very
  experimental
Why the History Lesson?
Ajax was never really planned
  Even today, the way it is used are is very
  experimental
Some uses, like Gmail and Google Maps, have been
amazing
Why the History Lesson?
Ajax was never really planned
  Even today, the way it is used are is very
  experimental
Some uses, like Gmail and Google Maps, have been
amazing
A lot more have been disastrous
Why the History Lesson?
Ajax was never really planned
  Even today, the way it is used are is very
  experimental
Some uses, like Gmail and Google Maps, have been
amazing
A lot more have been disastrous
Proceed with caution: a little Ajax goes a long way!
So What the Heck is it?
You can scroll from Edmond to Tulsa
and beyond without loading a Web page!
So What the Heck is it?
You can scroll from Edmond to Tulsa
and beyond without loading a Web page!
A Definition
A Definition

 Ajax is the process of
A Definition

 Ajax is the process of
   Using JavaScript to make a request to the server
A Definition

 Ajax is the process of
   Using JavaScript to make a request to the server
   Using the results of that request to dynamically
   modify the page the user is currently viewing
A Definition

 Ajax is the process of
   Using JavaScript to make a request to the server
   Using the results of that request to dynamically
   modify the page the user is currently viewing
 This request is not a full page load that moves the user
 to a new URL
The Upside
The Upside
Ajax can improve the user experience
The Upside
Ajax can improve the user experience
When used right, it sometimes makes Web applications
feel a bit more like desktop applications (think Gmail)
The Upside
Ajax can improve the user experience
When used right, it sometimes makes Web applications
feel a bit more like desktop applications (think Gmail)
It is generally faster
The Upside
Ajax can improve the user experience
When used right, it sometimes makes Web applications
feel a bit more like desktop applications (think Gmail)
It is generally faster
  A full page load is expensive: full HTML, CSS,
  JavaScript files, and typically several images
The Upside
Ajax can improve the user experience
When used right, it sometimes makes Web applications
feel a bit more like desktop applications (think Gmail)
It is generally faster
  A full page load is expensive: full HTML, CSS,
  JavaScript files, and typically several images
  Ajax requests usually load a lot less
Many Downsides
Many Downsides

Ajax interactions are usually much harder to debug
Many Downsides

Ajax interactions are usually much harder to debug
  Everything happens in the background, so it’s hard to
  see things go wrong
Many Downsides

Ajax interactions are usually much harder to debug
  Everything happens in the background, so it’s hard to
  see things go wrong
Badly planned Ajax actions can easily degrade the
interface experience instead of enhancing it
Many Downsides

Ajax interactions are usually much harder to debug
  Everything happens in the background, so it’s hard to
  see things go wrong
Badly planned Ajax actions can easily degrade the
interface experience instead of enhancing it
You lose addressability (a big advantage of the Web)
Addressability
Note that I arrived at http://maps.google.com/
Still at the Same URL
Most of the content has changed,
but I’m still at http://maps.google.com/
Still at the Same URL
Most of the content has changed,
but I’m still at http://maps.google.com/
Still at the Same URL
Most of the content has changed,
but I’m still at http://maps.google.com/
Ajax in Rails
There are many ways to handle Ajax with Rails
Rails has Ajax
Support Built-in
Rails has Ajax
Support Built-in
 Rails added a slew of Ajax helpers many versions ago
Rails has Ajax
Support Built-in
 Rails added a slew of Ajax helpers many versions ago
   At the time, they were very impressive
Rails has Ajax
Support Built-in
 Rails added a slew of Ajax helpers many versions ago
   At the time, they were very impressive
 We’ve learned better ways (experimental remember?)
Rails has Ajax
Support Built-in
 Rails added a slew of Ajax helpers many versions ago
   At the time, they were very impressive
 We’ve learned better ways (experimental remember?)
   The helpers have fallen out of fashion
Rails has Ajax
Support Built-in
 Rails added a slew of Ajax helpers many versions ago
   At the time, they were very impressive
 We’ve learned better ways (experimental remember?)
   The helpers have fallen out of fashion
 Rails is abandoning the old strategy in the next release
Rails has Ajax
Support Built-in
 Rails added a slew of Ajax helpers many versions ago
   At the time, they were very impressive
 We’ve learned better ways (experimental remember?)
   The helpers have fallen out of fashion
 Rails is abandoning the old strategy in the next release
   The helpers will be reworked, similar to what I am
   going to show you
Unobtrusive JavaScript
Unobtrusive JavaScript

Behavior (JavaScript) should be separated from
presentation (HTML and CSS)
Unobtrusive JavaScript

Behavior (JavaScript) should be separated from
presentation (HTML and CSS)
We should progressively enhance pages with
functionality
Unobtrusive JavaScript

Behavior (JavaScript) should be separated from
presentation (HTML and CSS)
We should progressively enhance pages with
functionality
  Agents not supporting the advanced functionality are
  just not enhanced
jQuery
jQuery
Rails uses the Prototype and script.aculo.us libraries
jQuery
Rails uses the Prototype and script.aculo.us libraries
I prefer jQuery
jQuery
Rails uses the Prototype and script.aculo.us libraries
I prefer jQuery
  It makes it very easy to select pieces of a Web page
jQuery
Rails uses the Prototype and script.aculo.us libraries
I prefer jQuery
  It makes it very easy to select pieces of a Web page
  It helps you manipulate what you have selected
jQuery
Rails uses the Prototype and script.aculo.us libraries
I prefer jQuery
  It makes it very easy to select pieces of a Web page
  It helps you manipulate what you have selected
  It handles events for you
jQuery
Rails uses the Prototype and script.aculo.us libraries
I prefer jQuery
  It makes it very easy to select pieces of a Web page
  It helps you manipulate what you have selected
  It handles events for you
  And it supports Ajax
jQuery Crash Course
jQuery Crash Course
Run when the DOM is ready: jQuery(function() { });
jQuery Crash Course
Run when the DOM is ready: jQuery(function() { });
Select with CSS: $(‘form#data input.autofill’)
jQuery Crash Course
Run when the DOM is ready: jQuery(function() { });
Select with CSS: $(‘form#data input.autofill’)
Run on click: $(‘…’).click(function() { });
jQuery Crash Course
Run when the DOM is ready: jQuery(function() { });
Select with CSS: $(‘form#data input.autofill’)
Run on click: $(‘…’).click(function() { });
Run on submit: $(‘form’).submit(function() { });
jQuery Crash Course
Run when the DOM is ready: jQuery(function() { });
Select with CSS: $(‘form#data input.autofill’)
Run on click: $(‘…’).click(function() { });
Run on submit: $(‘form’).submit(function() { });
Change content: $(‘…’).html(content);
jQuery Crash Course
Run when the DOM is ready: jQuery(function() { });
Select with CSS: $(‘form#data input.autofill’)
Run on click: $(‘…’).click(function() { });
Run on submit: $(‘form’).submit(function() { });
Change content: $(‘…’).html(content);
  Append content: $(‘…’).append(content);
Ajax With jQuery
jQuery gives you full control over how
the Ajax request is executed
$.ajax({
           url:     "http://ajaxapp.com/ajax_action",
           type:     "POST",
           dataType: "html",
           data:     $('form').serialize(),
           complete: function() {
             // called when complete
           },
           success: function() {
             // called when successful
           },
           error:    function() {
             // called when there is an error
           }
         });




Ajax With jQuery
jQuery gives you full control over how
the Ajax request is executed
$.ajax({
           url:     "http://ajaxapp.com/ajax_action",
           type:     "POST",
           dataType: "html",
           data:     $('form').serialize(),
           complete: function() {
             // called when complete
           },
           success: function() {
             // called when successful
           },
           error:    function() {
             // called when there is an error
           }
         });




Ajax With jQuery
jQuery gives you full control over how
the Ajax request is executed
$.ajax({
           url:     "http://ajaxapp.com/ajax_action",
           type:     "POST",
           dataType: "html",
           data:     $('form').serialize(),
           complete: function() {
             // called when complete
           },
           success: function() {
             // called when successful
           },
           error:    function() {
             // called when there is an error
           }
         });




Ajax With jQuery
jQuery gives you full control over how
the Ajax request is executed
$.ajax({
           url:     "http://ajaxapp.com/ajax_action",
           type:     "POST",
           dataType: "html",
           data:     $('form').serialize(),
           complete: function() {
             // called when complete
           },
           success: function() {
             // called when successful
           },
           error:    function() {
             // called when there is an error
           }
         });




Ajax With jQuery
jQuery gives you full control over how
the Ajax request is executed
$.ajax({
           url:     "http://ajaxapp.com/ajax_action",
           type:     "POST",
           dataType: "html",
           data:     $('form').serialize(),
           complete: function() {
             // called when complete
           },
           success: function() {
             // called when successful
           },
           error:    function() {
             // called when there is an error
           }
         });




Ajax With jQuery
jQuery gives you full control over how
the Ajax request is executed
An Example
Let’s take a look at an Ajax request in action
Commenting via Ajax
Commenting via Ajax

Let’s take a working blog comment system and convert
it to use Ajax (when JavaScript is available)
Commenting via Ajax

Let’s take a working blog comment system and convert
it to use Ajax (when JavaScript is available)
There’s no advantage to having the user visit a create
action
Commenting via Ajax

Let’s take a working blog comment system and convert
it to use Ajax (when JavaScript is available)
There’s no advantage to having the user visit a create
action
  We won’t lose addressability in this case
Commenting via Ajax

Let’s take a working blog comment system and convert
it to use Ajax (when JavaScript is available)
There’s no advantage to having the user visit a create
action
  We won’t lose addressability in this case
The Ajax request will require less resources from our
controller and be more responsive for the user
An Article With Comments
This is a trivial blog like interface,
allowing users to comment on articles
An Article With Comments
This is a trivial blog like interface,
allowing users to comment on articles
A Full Page Refresh
We loaded a lot of content that didn’t change
just to add that little comment
A Full Page Refresh
We loaded a lot of content that didn’t change
just to add that little comment
A Full Page Refresh
We loaded a lot of content that didn’t change
just to add that little comment
A Full Page Refresh
We loaded a lot of content that didn’t change
just to add that little comment
Add JavaScript
I have loaded jQuery from Google and
my own JavaScript file
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
              "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title><%= build_page_title yield(:page_title) %></title>
    <script type="text/javascript"
          src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <%= javascript_include_tag "application" %>
  </head>
  <body>
    <%= flash_messages %>
    <%= yield %>
  </body>
</html>




Add JavaScript
I have loaded jQuery from Google and
my own JavaScript file
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
              "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title><%= build_page_title yield(:page_title) %></title>
    <script type="text/javascript"
          src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <%= javascript_include_tag "application" %>
  </head>
  <body>
    <%= flash_messages %>
    <%= yield %>
  </body>
</html>




Add JavaScript
I have loaded jQuery from Google and
my own JavaScript file
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
              "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <title><%= build_page_title yield(:page_title) %></title>
    <script type="text/javascript"
          src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script>
    <%= javascript_include_tag "application" %>
  </head>
  <body>
    <%= flash_messages %>
    <%= yield %>
  </body>
</html>




Add JavaScript
I have loaded jQuery from Google and
my own JavaScript file
Prepare Form
I have added a little structure to the document
to assist me with the JavaScript manipulation
<h1><%= h @article.title %></h1>
     <%= simple_format @article.body %>

     <h2>Comments</h2>
     <div id="comments">
       <%= render @article.comments %>
     </div>

     <h3>Add a Comment</h3>
     <% form_for @comment || @article.comments.build,
            :html => {:id => "comment_form"} do |f| %>
       <%= f.error_messages                   %>
       <%= f.hidden_field :article_id           %>
       <%= f.label      :author             %><br>
       <%= f.text_field :author, :size => 42       %><br>
       <%= f.label      :body, "Comment"         %><br>
       <%= f.text_area :body, :cols => 40, :rows => 5 %><br>
       <%= f.submit "Comment"                   %>
       <span class="ajax_message">&nbsp;</span>
     <% end %>




Prepare Form
I have added a little structure to the document
to assist me with the JavaScript manipulation
<h1><%= h @article.title %></h1>
     <%= simple_format @article.body %>

     <h2>Comments</h2>
     <div id="comments">
       <%= render @article.comments %>
     </div>

     <h3>Add a Comment</h3>
     <% form_for @comment || @article.comments.build,
            :html => {:id => "comment_form"} do |f| %>
       <%= f.error_messages                   %>
       <%= f.hidden_field :article_id           %>
       <%= f.label      :author             %><br>
       <%= f.text_field :author, :size => 42       %><br>
       <%= f.label      :body, "Comment"         %><br>
       <%= f.text_area :body, :cols => 40, :rows => 5 %><br>
       <%= f.submit "Comment"                   %>
       <span class="ajax_message">&nbsp;</span>
     <% end %>




Prepare Form
I have added a little structure to the document
to assist me with the JavaScript manipulation
<h1><%= h @article.title %></h1>
     <%= simple_format @article.body %>

     <h2>Comments</h2>
     <div id="comments">
       <%= render @article.comments %>
     </div>

     <h3>Add a Comment</h3>
     <% form_for @comment || @article.comments.build,
            :html => {:id => "comment_form"} do |f| %>
       <%= f.error_messages                   %>
       <%= f.hidden_field :article_id           %>
       <%= f.label      :author             %><br>
       <%= f.text_field :author, :size => 42       %><br>
       <%= f.label      :body, "Comment"         %><br>
       <%= f.text_area :body, :cols => 40, :rows => 5 %><br>
       <%= f.submit "Comment"                   %>
       <span class="ajax_message">&nbsp;</span>
     <% end %>




Prepare Form
I have added a little structure to the document
to assist me with the JavaScript manipulation
<h1><%= h @article.title %></h1>
     <%= simple_format @article.body %>

     <h2>Comments</h2>
     <div id="comments">
       <%= render @article.comments %>
     </div>

     <h3>Add a Comment</h3>
     <% form_for @comment || @article.comments.build,
            :html => {:id => "comment_form"} do |f| %>
       <%= f.error_messages                   %>
       <%= f.hidden_field :article_id           %>
       <%= f.label      :author             %><br>
       <%= f.text_field :author, :size => 42       %><br>
       <%= f.label      :body, "Comment"         %><br>
       <%= f.text_area :body, :cols => 40, :rows => 5 %><br>
       <%= f.submit "Comment"                   %>
       <span class="ajax_message">&nbsp;</span>
     <% end %>




Prepare Form
I have added a little structure to the document
to assist me with the JavaScript manipulation
Build Ajax Request
We can pull the request details from the form,
but we have to do some manual interface work
jQuery(function() {
          $('#comment_form').submit(function(event) {
              event.preventDefault();
              var f = $(this);
              f.find('.ajax_message').html('Saving...');
              f.find('input[type="submit"]').attr('disabled', true);
              $.ajax({
                  url:    f.attr('action'),
                  type:     f.attr('method'),
                  dataType: "html",
                  data:     f.serialize(),
                  complete: function() {
                     f.find('.ajax_message').html('&nbsp;');
                     f.find('input[type="submit"]').attr('disabled', false);
                  },
                  success: function(data, textStatus, xhr) {
                     $('#comments').append(data);
                     f.find('input[type="text"], textarea').val('');
                  },
                  error: function() {
                     alert('Please enter an author and comment.');
                  },
              });
          });
      });




Build Ajax Request
We can pull the request details from the form,
but we have to do some manual interface work
jQuery(function() {
          $('#comment_form').submit(function(event) {
              event.preventDefault();
              var f = $(this);
              f.find('.ajax_message').html('Saving...');
              f.find('input[type="submit"]').attr('disabled', true);
              $.ajax({
                  url:    f.attr('action'),
                  type:     f.attr('method'),
                  dataType: "html",
                  data:     f.serialize(),
                  complete: function() {
                     f.find('.ajax_message').html('&nbsp;');
                     f.find('input[type="submit"]').attr('disabled', false);
                  },
                  success: function(data, textStatus, xhr) {
                     $('#comments').append(data);
                     f.find('input[type="text"], textarea').val('');
                  },
                  error: function() {
                     alert('Please enter an author and comment.');
                  },
              });
          });
      });




Build Ajax Request
We can pull the request details from the form,
but we have to do some manual interface work
jQuery(function() {
          $('#comment_form').submit(function(event) {
              event.preventDefault();
              var f = $(this);
              f.find('.ajax_message').html('Saving...');
              f.find('input[type="submit"]').attr('disabled', true);
              $.ajax({
                  url:    f.attr('action'),
                  type:     f.attr('method'),
                  dataType: "html",
                  data:     f.serialize(),
                  complete: function() {
                     f.find('.ajax_message').html('&nbsp;');
                     f.find('input[type="submit"]').attr('disabled', false);
                  },
                  success: function(data, textStatus, xhr) {
                     $('#comments').append(data);
                     f.find('input[type="text"], textarea').val('');
                  },
                  error: function() {
                     alert('Please enter an author and comment.');
                  },
              });
          });
      });




Build Ajax Request
We can pull the request details from the form,
but we have to do some manual interface work
jQuery(function() {
          $('#comment_form').submit(function(event) {
              event.preventDefault();
              var f = $(this);
              f.find('.ajax_message').html('Saving...');
              f.find('input[type="submit"]').attr('disabled', true);
              $.ajax({
                  url:    f.attr('action'),
                  type:     f.attr('method'),
                  dataType: "html",
                  data:     f.serialize(),
                  complete: function() {
                     f.find('.ajax_message').html('&nbsp;');
                     f.find('input[type="submit"]').attr('disabled', false);
                  },
                  success: function(data, textStatus, xhr) {
                     $('#comments').append(data);
                     f.find('input[type="text"], textarea').val('');
                  },
                  error: function() {
                     alert('Please enter an author and comment.');
                  },
              });
          });
      });




Build Ajax Request
We can pull the request details from the form,
but we have to do some manual interface work
jQuery(function() {
          $('#comment_form').submit(function(event) {
              event.preventDefault();
              var f = $(this);
              f.find('.ajax_message').html('Saving...');
              f.find('input[type="submit"]').attr('disabled', true);
              $.ajax({
                  url:    f.attr('action'),
                  type:     f.attr('method'),
                  dataType: "html",
                  data:     f.serialize(),
                  complete: function() {
                     f.find('.ajax_message').html('&nbsp;');
                     f.find('input[type="submit"]').attr('disabled', false);
                  },
                  success: function(data, textStatus, xhr) {
                     $('#comments').append(data);
                     f.find('input[type="text"], textarea').val('');
                  },
                  error: function() {
                     alert('Please enter an author and comment.');
                  },
              });
          });
      });




Build Ajax Request
We can pull the request details from the form,
but we have to do some manual interface work
Respond to Ajax
Remember XMLHttpRequest (“xhr”)?
We respond with just the comment.
class CommentsController < ApplicationController
        def create
          @comment = Comment.new(params[:comment])
          if @comment.save
            if request.xhr?
              render @comment
            else
              flash[:notice] = "Comment added."
              redirect_to article_path(@comment.article)
            end
          else
            if request.xhr?
              render :status => 403
            else
              flash[:error] = "Comment could not be added."
              redirect_to article_path(@comment.article)
            end
          end
        end
       end




Respond to Ajax
Remember XMLHttpRequest (“xhr”)?
We respond with just the comment.
class CommentsController < ApplicationController
        def create
          @comment = Comment.new(params[:comment])
          if @comment.save
            if request.xhr?
              render @comment
            else
              flash[:notice] = "Comment added."
              redirect_to article_path(@comment.article)
            end
          else
            if request.xhr?
              render :status => 403
            else
              flash[:error] = "Comment could not be added."
              redirect_to article_path(@comment.article)
            end
          end
        end
       end




Respond to Ajax
Remember XMLHttpRequest (“xhr”)?
We respond with just the comment.
class CommentsController < ApplicationController
        def create
          @comment = Comment.new(params[:comment])
          if @comment.save
            if request.xhr?
              render @comment
            else
              flash[:notice] = "Comment added."
              redirect_to article_path(@comment.article)
            end
          else
            if request.xhr?
              render :status => 403
            else
              flash[:error] = "Comment could not be added."
              redirect_to article_path(@comment.article)
            end
          end
        end
       end




Respond to Ajax
Remember XMLHttpRequest (“xhr”)?
We respond with just the comment.
class CommentsController < ApplicationController
        def create
          @comment = Comment.new(params[:comment])
          if @comment.save
            if request.xhr?
              render @comment
            else
              flash[:notice] = "Comment added."
              redirect_to article_path(@comment.article)
            end
          else
            if request.xhr?
              render :status => 403
            else
              flash[:error] = "Comment could not be added."
              redirect_to article_path(@comment.article)
            end
          end
        end
       end




Respond to Ajax
Remember XMLHttpRequest (“xhr”)?
We respond with just the comment.
Sending Ajax
I have provided some interface clues
so the user knows work is in progress
Sending Ajax
I have provided some interface clues
so the user knows work is in progress
Sending Ajax
I have provided some interface clues
so the user knows work is in progress
Ajax Complete
This time we loaded much less data,
but we had to do more interface cleanup
Ajax Complete
This time we loaded much less data,
but we had to do more interface cleanup
Ajax Complete
This time we loaded much less data,
but we had to do more interface cleanup
Ajax Complete
This time we loaded much less data,
but we had to do more interface cleanup
Mind the Details
Mind the Details
 With Ajax, you need to manage the interface details
Mind the Details
 With Ajax, you need to manage the interface details
   I added a “Saving…” indicator
Mind the Details
 With Ajax, you need to manage the interface details
   I added a “Saving…” indicator
   I disabled the “Comment” button
Mind the Details
 With Ajax, you need to manage the interface details
   I added a “Saving…” indicator
   I disabled the “Comment” button
   I undid both of the above when the request finished
Mind the Details
 With Ajax, you need to manage the interface details
   I added a “Saving…” indicator
   I disabled the “Comment” button
   I undid both of the above when the request finished
   I cleared the form for new entries
Mind the Details
 With Ajax, you need to manage the interface details
   I added a “Saving…” indicator
   I disabled the “Comment” button
   I undid both of the above when the request finished
   I cleared the form for new entries
   I showed a reasonable error message for failure
Questions?
Ajax Lab
Your book has instructions on how to add some
Ajax page manipulations to your application

Contenu connexe

Plus de James Gray

Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)James Gray
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHubJames Gray
 
Test Coverage in Rails
Test Coverage in RailsTest Coverage in Rails
Test Coverage in RailsJames Gray
 
Rails Routing And Rendering
Rails Routing And RenderingRails Routing And Rendering
Rails Routing And RenderingJames Gray
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with RailsJames Gray
 
Associations in Rails
Associations in RailsAssociations in Rails
Associations in RailsJames Gray
 
DRYing Up Rails Views and Controllers
DRYing Up Rails Views and ControllersDRYing Up Rails Views and Controllers
DRYing Up Rails Views and ControllersJames Gray
 
Building a Rails Interface
Building a Rails InterfaceBuilding a Rails Interface
Building a Rails InterfaceJames Gray
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model BasicsJames Gray
 
Wed Development on Rails
Wed Development on RailsWed Development on Rails
Wed Development on RailsJames Gray
 

Plus de James Gray (12)

API Design
API DesignAPI Design
API Design
 
Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)Amazon's Simple Storage Service (S3)
Amazon's Simple Storage Service (S3)
 
Git and GitHub
Git and GitHubGit and GitHub
Git and GitHub
 
Test Coverage in Rails
Test Coverage in RailsTest Coverage in Rails
Test Coverage in Rails
 
Rails Routing And Rendering
Rails Routing And RenderingRails Routing And Rendering
Rails Routing And Rendering
 
Sending Email with Rails
Sending Email with RailsSending Email with Rails
Sending Email with Rails
 
Associations in Rails
Associations in RailsAssociations in Rails
Associations in Rails
 
DRYing Up Rails Views and Controllers
DRYing Up Rails Views and ControllersDRYing Up Rails Views and Controllers
DRYing Up Rails Views and Controllers
 
Building a Rails Interface
Building a Rails InterfaceBuilding a Rails Interface
Building a Rails Interface
 
Rails Model Basics
Rails Model BasicsRails Model Basics
Rails Model Basics
 
Ruby
RubyRuby
Ruby
 
Wed Development on Rails
Wed Development on RailsWed Development on Rails
Wed Development on Rails
 

Dernier

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxLoriGlavin3
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxLoriGlavin3
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 

Dernier (20)

Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptxPasskey Providers and Enabling Portability: FIDO Paris Seminar.pptx
Passkey Providers and Enabling Portability: FIDO Paris Seminar.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptxThe Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
The Fit for Passkeys for Employee and Consumer Sign-ins: FIDO Paris Seminar.pptx
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 

Ajax with jQuery in Rails

  • 1. Ajax The quest to turn Web applications into desktop applications
  • 2. What is Ajax? It’s hard to avoid hearing about Ajax in Web discussions these days, but what is it really?
  • 4. What’s in a Name? The term originally stood for “Asynchronous JavaScript and XML”
  • 5. What’s in a Name? The term originally stood for “Asynchronous JavaScript and XML” But it doesn’t have to be asynchronous
  • 6. What’s in a Name? The term originally stood for “Asynchronous JavaScript and XML” But it doesn’t have to be asynchronous Or involve XML
  • 7. What’s in a Name? The term originally stood for “Asynchronous JavaScript and XML” But it doesn’t have to be asynchronous Or involve XML Nowadays the term pretty much stands on its own
  • 9. The Accidental Feature It’s hard to change the Web
  • 10. The Accidental Feature It’s hard to change the Web You need to get through standards committees
  • 11. The Accidental Feature It’s hard to change the Web You need to get through standards committees And it doesn’t really count until most browsers agree
  • 12. The Accidental Feature It’s hard to change the Web You need to get through standards committees And it doesn’t really count until most browsers agree In 1999 Microsoft added an XMLHTTP ActiveX control
  • 13. The Accidental Feature It’s hard to change the Web You need to get through standards committees And it doesn’t really count until most browsers agree In 1999 Microsoft added an XMLHTTP ActiveX control Not to be outdone, Mozilla, Safari, and Opera copied it, adding native XMLHttpRequest objects
  • 14. The Accidental Feature It’s hard to change the Web You need to get through standards committees And it doesn’t really count until most browsers agree In 1999 Microsoft added an XMLHTTP ActiveX control Not to be outdone, Mozilla, Safari, and Opera copied it, adding native XMLHttpRequest objects No one really knew what to do with it
  • 16. Someone Figured it Out! Google figured out the browsers had all learned a new trick
  • 17. Someone Figured it Out! Google figured out the browsers had all learned a new trick They put it to use
  • 18. Someone Figured it Out! Google figured out the browsers had all learned a new trick They put it to use Gmail, 2004
  • 19. Someone Figured it Out! Google figured out the browsers had all learned a new trick They put it to use Gmail, 2004 Google Maps, 2005
  • 20. Someone Figured it Out! Google figured out the browsers had all learned a new trick They put it to use Gmail, 2004 Google Maps, 2005 Ajax was born
  • 21. Why the History Lesson?
  • 22. Why the History Lesson? Ajax was never really planned
  • 23. Why the History Lesson? Ajax was never really planned Even today, the way it is used are is very experimental
  • 24. Why the History Lesson? Ajax was never really planned Even today, the way it is used are is very experimental Some uses, like Gmail and Google Maps, have been amazing
  • 25. Why the History Lesson? Ajax was never really planned Even today, the way it is used are is very experimental Some uses, like Gmail and Google Maps, have been amazing A lot more have been disastrous
  • 26. Why the History Lesson? Ajax was never really planned Even today, the way it is used are is very experimental Some uses, like Gmail and Google Maps, have been amazing A lot more have been disastrous Proceed with caution: a little Ajax goes a long way!
  • 27. So What the Heck is it? You can scroll from Edmond to Tulsa and beyond without loading a Web page!
  • 28. So What the Heck is it? You can scroll from Edmond to Tulsa and beyond without loading a Web page!
  • 30. A Definition Ajax is the process of
  • 31. A Definition Ajax is the process of Using JavaScript to make a request to the server
  • 32. A Definition Ajax is the process of Using JavaScript to make a request to the server Using the results of that request to dynamically modify the page the user is currently viewing
  • 33. A Definition Ajax is the process of Using JavaScript to make a request to the server Using the results of that request to dynamically modify the page the user is currently viewing This request is not a full page load that moves the user to a new URL
  • 35. The Upside Ajax can improve the user experience
  • 36. The Upside Ajax can improve the user experience When used right, it sometimes makes Web applications feel a bit more like desktop applications (think Gmail)
  • 37. The Upside Ajax can improve the user experience When used right, it sometimes makes Web applications feel a bit more like desktop applications (think Gmail) It is generally faster
  • 38. The Upside Ajax can improve the user experience When used right, it sometimes makes Web applications feel a bit more like desktop applications (think Gmail) It is generally faster A full page load is expensive: full HTML, CSS, JavaScript files, and typically several images
  • 39. The Upside Ajax can improve the user experience When used right, it sometimes makes Web applications feel a bit more like desktop applications (think Gmail) It is generally faster A full page load is expensive: full HTML, CSS, JavaScript files, and typically several images Ajax requests usually load a lot less
  • 41. Many Downsides Ajax interactions are usually much harder to debug
  • 42. Many Downsides Ajax interactions are usually much harder to debug Everything happens in the background, so it’s hard to see things go wrong
  • 43. Many Downsides Ajax interactions are usually much harder to debug Everything happens in the background, so it’s hard to see things go wrong Badly planned Ajax actions can easily degrade the interface experience instead of enhancing it
  • 44. Many Downsides Ajax interactions are usually much harder to debug Everything happens in the background, so it’s hard to see things go wrong Badly planned Ajax actions can easily degrade the interface experience instead of enhancing it You lose addressability (a big advantage of the Web)
  • 45. Addressability Note that I arrived at http://maps.google.com/
  • 46. Still at the Same URL Most of the content has changed, but I’m still at http://maps.google.com/
  • 47. Still at the Same URL Most of the content has changed, but I’m still at http://maps.google.com/
  • 48. Still at the Same URL Most of the content has changed, but I’m still at http://maps.google.com/
  • 49. Ajax in Rails There are many ways to handle Ajax with Rails
  • 51. Rails has Ajax Support Built-in Rails added a slew of Ajax helpers many versions ago
  • 52. Rails has Ajax Support Built-in Rails added a slew of Ajax helpers many versions ago At the time, they were very impressive
  • 53. Rails has Ajax Support Built-in Rails added a slew of Ajax helpers many versions ago At the time, they were very impressive We’ve learned better ways (experimental remember?)
  • 54. Rails has Ajax Support Built-in Rails added a slew of Ajax helpers many versions ago At the time, they were very impressive We’ve learned better ways (experimental remember?) The helpers have fallen out of fashion
  • 55. Rails has Ajax Support Built-in Rails added a slew of Ajax helpers many versions ago At the time, they were very impressive We’ve learned better ways (experimental remember?) The helpers have fallen out of fashion Rails is abandoning the old strategy in the next release
  • 56. Rails has Ajax Support Built-in Rails added a slew of Ajax helpers many versions ago At the time, they were very impressive We’ve learned better ways (experimental remember?) The helpers have fallen out of fashion Rails is abandoning the old strategy in the next release The helpers will be reworked, similar to what I am going to show you
  • 58. Unobtrusive JavaScript Behavior (JavaScript) should be separated from presentation (HTML and CSS)
  • 59. Unobtrusive JavaScript Behavior (JavaScript) should be separated from presentation (HTML and CSS) We should progressively enhance pages with functionality
  • 60. Unobtrusive JavaScript Behavior (JavaScript) should be separated from presentation (HTML and CSS) We should progressively enhance pages with functionality Agents not supporting the advanced functionality are just not enhanced
  • 62. jQuery Rails uses the Prototype and script.aculo.us libraries
  • 63. jQuery Rails uses the Prototype and script.aculo.us libraries I prefer jQuery
  • 64. jQuery Rails uses the Prototype and script.aculo.us libraries I prefer jQuery It makes it very easy to select pieces of a Web page
  • 65. jQuery Rails uses the Prototype and script.aculo.us libraries I prefer jQuery It makes it very easy to select pieces of a Web page It helps you manipulate what you have selected
  • 66. jQuery Rails uses the Prototype and script.aculo.us libraries I prefer jQuery It makes it very easy to select pieces of a Web page It helps you manipulate what you have selected It handles events for you
  • 67. jQuery Rails uses the Prototype and script.aculo.us libraries I prefer jQuery It makes it very easy to select pieces of a Web page It helps you manipulate what you have selected It handles events for you And it supports Ajax
  • 69. jQuery Crash Course Run when the DOM is ready: jQuery(function() { });
  • 70. jQuery Crash Course Run when the DOM is ready: jQuery(function() { }); Select with CSS: $(‘form#data input.autofill’)
  • 71. jQuery Crash Course Run when the DOM is ready: jQuery(function() { }); Select with CSS: $(‘form#data input.autofill’) Run on click: $(‘…’).click(function() { });
  • 72. jQuery Crash Course Run when the DOM is ready: jQuery(function() { }); Select with CSS: $(‘form#data input.autofill’) Run on click: $(‘…’).click(function() { }); Run on submit: $(‘form’).submit(function() { });
  • 73. jQuery Crash Course Run when the DOM is ready: jQuery(function() { }); Select with CSS: $(‘form#data input.autofill’) Run on click: $(‘…’).click(function() { }); Run on submit: $(‘form’).submit(function() { }); Change content: $(‘…’).html(content);
  • 74. jQuery Crash Course Run when the DOM is ready: jQuery(function() { }); Select with CSS: $(‘form#data input.autofill’) Run on click: $(‘…’).click(function() { }); Run on submit: $(‘form’).submit(function() { }); Change content: $(‘…’).html(content); Append content: $(‘…’).append(content);
  • 75. Ajax With jQuery jQuery gives you full control over how the Ajax request is executed
  • 76. $.ajax({ url: "http://ajaxapp.com/ajax_action", type: "POST", dataType: "html", data: $('form').serialize(), complete: function() { // called when complete }, success: function() { // called when successful }, error: function() { // called when there is an error } }); Ajax With jQuery jQuery gives you full control over how the Ajax request is executed
  • 77. $.ajax({ url: "http://ajaxapp.com/ajax_action", type: "POST", dataType: "html", data: $('form').serialize(), complete: function() { // called when complete }, success: function() { // called when successful }, error: function() { // called when there is an error } }); Ajax With jQuery jQuery gives you full control over how the Ajax request is executed
  • 78. $.ajax({ url: "http://ajaxapp.com/ajax_action", type: "POST", dataType: "html", data: $('form').serialize(), complete: function() { // called when complete }, success: function() { // called when successful }, error: function() { // called when there is an error } }); Ajax With jQuery jQuery gives you full control over how the Ajax request is executed
  • 79. $.ajax({ url: "http://ajaxapp.com/ajax_action", type: "POST", dataType: "html", data: $('form').serialize(), complete: function() { // called when complete }, success: function() { // called when successful }, error: function() { // called when there is an error } }); Ajax With jQuery jQuery gives you full control over how the Ajax request is executed
  • 80. $.ajax({ url: "http://ajaxapp.com/ajax_action", type: "POST", dataType: "html", data: $('form').serialize(), complete: function() { // called when complete }, success: function() { // called when successful }, error: function() { // called when there is an error } }); Ajax With jQuery jQuery gives you full control over how the Ajax request is executed
  • 81. An Example Let’s take a look at an Ajax request in action
  • 83. Commenting via Ajax Let’s take a working blog comment system and convert it to use Ajax (when JavaScript is available)
  • 84. Commenting via Ajax Let’s take a working blog comment system and convert it to use Ajax (when JavaScript is available) There’s no advantage to having the user visit a create action
  • 85. Commenting via Ajax Let’s take a working blog comment system and convert it to use Ajax (when JavaScript is available) There’s no advantage to having the user visit a create action We won’t lose addressability in this case
  • 86. Commenting via Ajax Let’s take a working blog comment system and convert it to use Ajax (when JavaScript is available) There’s no advantage to having the user visit a create action We won’t lose addressability in this case The Ajax request will require less resources from our controller and be more responsive for the user
  • 87. An Article With Comments This is a trivial blog like interface, allowing users to comment on articles
  • 88. An Article With Comments This is a trivial blog like interface, allowing users to comment on articles
  • 89. A Full Page Refresh We loaded a lot of content that didn’t change just to add that little comment
  • 90. A Full Page Refresh We loaded a lot of content that didn’t change just to add that little comment
  • 91. A Full Page Refresh We loaded a lot of content that didn’t change just to add that little comment
  • 92. A Full Page Refresh We loaded a lot of content that didn’t change just to add that little comment
  • 93. Add JavaScript I have loaded jQuery from Google and my own JavaScript file
  • 94. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title><%= build_page_title yield(:page_title) %></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <%= javascript_include_tag "application" %> </head> <body> <%= flash_messages %> <%= yield %> </body> </html> Add JavaScript I have loaded jQuery from Google and my own JavaScript file
  • 95. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title><%= build_page_title yield(:page_title) %></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <%= javascript_include_tag "application" %> </head> <body> <%= flash_messages %> <%= yield %> </body> </html> Add JavaScript I have loaded jQuery from Google and my own JavaScript file
  • 96. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"> <title><%= build_page_title yield(:page_title) %></title> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.min.js"></script> <%= javascript_include_tag "application" %> </head> <body> <%= flash_messages %> <%= yield %> </body> </html> Add JavaScript I have loaded jQuery from Google and my own JavaScript file
  • 97. Prepare Form I have added a little structure to the document to assist me with the JavaScript manipulation
  • 98. <h1><%= h @article.title %></h1> <%= simple_format @article.body %> <h2>Comments</h2> <div id="comments"> <%= render @article.comments %> </div> <h3>Add a Comment</h3> <% form_for @comment || @article.comments.build, :html => {:id => "comment_form"} do |f| %> <%= f.error_messages %> <%= f.hidden_field :article_id %> <%= f.label :author %><br> <%= f.text_field :author, :size => 42 %><br> <%= f.label :body, "Comment" %><br> <%= f.text_area :body, :cols => 40, :rows => 5 %><br> <%= f.submit "Comment" %> <span class="ajax_message">&nbsp;</span> <% end %> Prepare Form I have added a little structure to the document to assist me with the JavaScript manipulation
  • 99. <h1><%= h @article.title %></h1> <%= simple_format @article.body %> <h2>Comments</h2> <div id="comments"> <%= render @article.comments %> </div> <h3>Add a Comment</h3> <% form_for @comment || @article.comments.build, :html => {:id => "comment_form"} do |f| %> <%= f.error_messages %> <%= f.hidden_field :article_id %> <%= f.label :author %><br> <%= f.text_field :author, :size => 42 %><br> <%= f.label :body, "Comment" %><br> <%= f.text_area :body, :cols => 40, :rows => 5 %><br> <%= f.submit "Comment" %> <span class="ajax_message">&nbsp;</span> <% end %> Prepare Form I have added a little structure to the document to assist me with the JavaScript manipulation
  • 100. <h1><%= h @article.title %></h1> <%= simple_format @article.body %> <h2>Comments</h2> <div id="comments"> <%= render @article.comments %> </div> <h3>Add a Comment</h3> <% form_for @comment || @article.comments.build, :html => {:id => "comment_form"} do |f| %> <%= f.error_messages %> <%= f.hidden_field :article_id %> <%= f.label :author %><br> <%= f.text_field :author, :size => 42 %><br> <%= f.label :body, "Comment" %><br> <%= f.text_area :body, :cols => 40, :rows => 5 %><br> <%= f.submit "Comment" %> <span class="ajax_message">&nbsp;</span> <% end %> Prepare Form I have added a little structure to the document to assist me with the JavaScript manipulation
  • 101. <h1><%= h @article.title %></h1> <%= simple_format @article.body %> <h2>Comments</h2> <div id="comments"> <%= render @article.comments %> </div> <h3>Add a Comment</h3> <% form_for @comment || @article.comments.build, :html => {:id => "comment_form"} do |f| %> <%= f.error_messages %> <%= f.hidden_field :article_id %> <%= f.label :author %><br> <%= f.text_field :author, :size => 42 %><br> <%= f.label :body, "Comment" %><br> <%= f.text_area :body, :cols => 40, :rows => 5 %><br> <%= f.submit "Comment" %> <span class="ajax_message">&nbsp;</span> <% end %> Prepare Form I have added a little structure to the document to assist me with the JavaScript manipulation
  • 102. Build Ajax Request We can pull the request details from the form, but we have to do some manual interface work
  • 103. jQuery(function() { $('#comment_form').submit(function(event) { event.preventDefault(); var f = $(this); f.find('.ajax_message').html('Saving...'); f.find('input[type="submit"]').attr('disabled', true); $.ajax({ url: f.attr('action'), type: f.attr('method'), dataType: "html", data: f.serialize(), complete: function() { f.find('.ajax_message').html('&nbsp;'); f.find('input[type="submit"]').attr('disabled', false); }, success: function(data, textStatus, xhr) { $('#comments').append(data); f.find('input[type="text"], textarea').val(''); }, error: function() { alert('Please enter an author and comment.'); }, }); }); }); Build Ajax Request We can pull the request details from the form, but we have to do some manual interface work
  • 104. jQuery(function() { $('#comment_form').submit(function(event) { event.preventDefault(); var f = $(this); f.find('.ajax_message').html('Saving...'); f.find('input[type="submit"]').attr('disabled', true); $.ajax({ url: f.attr('action'), type: f.attr('method'), dataType: "html", data: f.serialize(), complete: function() { f.find('.ajax_message').html('&nbsp;'); f.find('input[type="submit"]').attr('disabled', false); }, success: function(data, textStatus, xhr) { $('#comments').append(data); f.find('input[type="text"], textarea').val(''); }, error: function() { alert('Please enter an author and comment.'); }, }); }); }); Build Ajax Request We can pull the request details from the form, but we have to do some manual interface work
  • 105. jQuery(function() { $('#comment_form').submit(function(event) { event.preventDefault(); var f = $(this); f.find('.ajax_message').html('Saving...'); f.find('input[type="submit"]').attr('disabled', true); $.ajax({ url: f.attr('action'), type: f.attr('method'), dataType: "html", data: f.serialize(), complete: function() { f.find('.ajax_message').html('&nbsp;'); f.find('input[type="submit"]').attr('disabled', false); }, success: function(data, textStatus, xhr) { $('#comments').append(data); f.find('input[type="text"], textarea').val(''); }, error: function() { alert('Please enter an author and comment.'); }, }); }); }); Build Ajax Request We can pull the request details from the form, but we have to do some manual interface work
  • 106. jQuery(function() { $('#comment_form').submit(function(event) { event.preventDefault(); var f = $(this); f.find('.ajax_message').html('Saving...'); f.find('input[type="submit"]').attr('disabled', true); $.ajax({ url: f.attr('action'), type: f.attr('method'), dataType: "html", data: f.serialize(), complete: function() { f.find('.ajax_message').html('&nbsp;'); f.find('input[type="submit"]').attr('disabled', false); }, success: function(data, textStatus, xhr) { $('#comments').append(data); f.find('input[type="text"], textarea').val(''); }, error: function() { alert('Please enter an author and comment.'); }, }); }); }); Build Ajax Request We can pull the request details from the form, but we have to do some manual interface work
  • 107. jQuery(function() { $('#comment_form').submit(function(event) { event.preventDefault(); var f = $(this); f.find('.ajax_message').html('Saving...'); f.find('input[type="submit"]').attr('disabled', true); $.ajax({ url: f.attr('action'), type: f.attr('method'), dataType: "html", data: f.serialize(), complete: function() { f.find('.ajax_message').html('&nbsp;'); f.find('input[type="submit"]').attr('disabled', false); }, success: function(data, textStatus, xhr) { $('#comments').append(data); f.find('input[type="text"], textarea').val(''); }, error: function() { alert('Please enter an author and comment.'); }, }); }); }); Build Ajax Request We can pull the request details from the form, but we have to do some manual interface work
  • 108. Respond to Ajax Remember XMLHttpRequest (“xhr”)? We respond with just the comment.
  • 109. class CommentsController < ApplicationController def create @comment = Comment.new(params[:comment]) if @comment.save if request.xhr? render @comment else flash[:notice] = "Comment added." redirect_to article_path(@comment.article) end else if request.xhr? render :status => 403 else flash[:error] = "Comment could not be added." redirect_to article_path(@comment.article) end end end end Respond to Ajax Remember XMLHttpRequest (“xhr”)? We respond with just the comment.
  • 110. class CommentsController < ApplicationController def create @comment = Comment.new(params[:comment]) if @comment.save if request.xhr? render @comment else flash[:notice] = "Comment added." redirect_to article_path(@comment.article) end else if request.xhr? render :status => 403 else flash[:error] = "Comment could not be added." redirect_to article_path(@comment.article) end end end end Respond to Ajax Remember XMLHttpRequest (“xhr”)? We respond with just the comment.
  • 111. class CommentsController < ApplicationController def create @comment = Comment.new(params[:comment]) if @comment.save if request.xhr? render @comment else flash[:notice] = "Comment added." redirect_to article_path(@comment.article) end else if request.xhr? render :status => 403 else flash[:error] = "Comment could not be added." redirect_to article_path(@comment.article) end end end end Respond to Ajax Remember XMLHttpRequest (“xhr”)? We respond with just the comment.
  • 112. class CommentsController < ApplicationController def create @comment = Comment.new(params[:comment]) if @comment.save if request.xhr? render @comment else flash[:notice] = "Comment added." redirect_to article_path(@comment.article) end else if request.xhr? render :status => 403 else flash[:error] = "Comment could not be added." redirect_to article_path(@comment.article) end end end end Respond to Ajax Remember XMLHttpRequest (“xhr”)? We respond with just the comment.
  • 113. Sending Ajax I have provided some interface clues so the user knows work is in progress
  • 114. Sending Ajax I have provided some interface clues so the user knows work is in progress
  • 115. Sending Ajax I have provided some interface clues so the user knows work is in progress
  • 116. Ajax Complete This time we loaded much less data, but we had to do more interface cleanup
  • 117. Ajax Complete This time we loaded much less data, but we had to do more interface cleanup
  • 118. Ajax Complete This time we loaded much less data, but we had to do more interface cleanup
  • 119. Ajax Complete This time we loaded much less data, but we had to do more interface cleanup
  • 121. Mind the Details With Ajax, you need to manage the interface details
  • 122. Mind the Details With Ajax, you need to manage the interface details I added a “Saving…” indicator
  • 123. Mind the Details With Ajax, you need to manage the interface details I added a “Saving…” indicator I disabled the “Comment” button
  • 124. Mind the Details With Ajax, you need to manage the interface details I added a “Saving…” indicator I disabled the “Comment” button I undid both of the above when the request finished
  • 125. Mind the Details With Ajax, you need to manage the interface details I added a “Saving…” indicator I disabled the “Comment” button I undid both of the above when the request finished I cleared the form for new entries
  • 126. Mind the Details With Ajax, you need to manage the interface details I added a “Saving…” indicator I disabled the “Comment” button I undid both of the above when the request finished I cleared the form for new entries I showed a reasonable error message for failure
  • 128. Ajax Lab Your book has instructions on how to add some Ajax page manipulations to your application

Notes de l'éditeur