SlideShare a Scribd company logo
1 of 30
Download to read offline
jQuery & Rails
          Best Friends Forever*

            Best Friends Forever*




       *Forever as used by a 6th-grader

  *Forever in the sense of a sixth grader.
I'll Cover:
●   Brief Rails explanation

●   Brief jQuery explanation

●   Nice methods between each technology to encourage a rich web app

    ●   AJAX

    ●   JSON

    ●   data
●   The Future
jQuery...
●   is a JavaScript framework (YUI, prototype, scriptaculous)

●   includes basic JavaScript functionality for AJAX, DOM manipulation,
    events

●   likes to hang out with jQuery UI, user interface library, interactions,
    widgets, effects, themes

●   is known for being concise and readable




                               http://jqueryui.com/
Popularity




http://www.webappers.com/infographics/javascript-frameworks-jquery.html
Ruby on Rails...
●   is a MVC framework built on
    Ruby

●   is a tool for efficient development
    that follows universal conventions

●   is designed to work well with
    JavaScript + AJAX
AJAX                in jQuery
$.ajax({
      url: "test.html",
      data: $('#form').serialize(),
      type: “POST”,
      cache: false,
      dataType: “html”,
      success: function(){
           //do something
      },
      error: function() {
           //do something else
      }
});
                                 http://api.jquery.com/jQuery.ajax/
Rails Tidbits
●   Routing: connects URLs to Code
    match “/products/:id” => “products#show”


●   Handling different responses
    respond_to do |format|
     format.html
     format.xml { … }
    end


●   Handling JSON response
    respond_to do |format|
     format.json { render :json => data }
    end
Rails Tidbits
●   Request object
    request.xhr?


●   Handling CGI parameters
    params[:name], params[:description]
    params.has_key?(:name)


    p = Product.new(params[:product])
    p.save # check for p.errors


    product.update_attributes(params[:product])
Pong




http://www.bafta.org/awards/video-games/play-pong-online,678,BA.html
User: Initiates Action
           //jQuery wrapper method
           $.fn.comment_photo = function() {
                //do stuff
           }


           $(function() {
                $('.comment-photo').click(function() {
                      $(this).comment_photo();
                });
           })
jQuery: AJAX call
  $.fn.comment_photo = function() {
      $.ajax({
            url: “/comment/new",
            data: {
                 photo_id: this.attr('id')
            },
            cache: false,
            dataType: “html”
            …
      });
  }
Rails: calls Controller
class CommentsController < ApplicationController
 def new
  @comment = Comment.new
  respond_to do |format|
      format.html #new.html.erb
  end
 end
end
Rails: renders HTML
            erb                                       HTML
<% form_for @comment do |f| %>     <form action= “/comments” method=”post”>
 <%= f.label :title %>             <label for=“comment_title”>Title</label>
 <%= f.text_field :title %>        <input type=“text” id=“comment_title” name=“comment[title]” />


 <%= f.label :data %>              <label for=“comment_data”>Data</label>
 <%= f.text_area :data %>          <textarea id=“comment_data” name=“comment[data]” /></textarea>


 <%= f.submit %>                   <input type=“submit” id=“comment_submit” value=”Create ” />
<% end %>                          </form>




                         http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/
jQuery: displays HTML
    $.fn.comment_photo = function() {
        $.ajax({
              …
              success: function(html) {
                  $('#new_comment').html(html);
              }
        });
    }
User: more action
        //extending jQuery object
        $.extend({
              create_comment: function(form) {
                    //do stuff
              }
        });


        $(function() {
              $('#new_comment').submit(function() {
                    $.create_comment($(this));
              });
        })
jQuery: AJAX call
   create_comment: function(form) {
       $.ajax({
             url: form.attr('action'),
             type: “POST”,
             data: {
                  comment: form.serialize()
             },
             cache: false,
             dataType: “JSON”
             …
       });
   }
Rails: calls Controller
 class CommentsController < ApplicationController
  def create
   begin
       comment = Comment.new(params[:comment])
       comment.user = current_user
       comment.save
       respond_to do |format|
        format.json :json => comment
       end
   rescue Exception => e
       render :status => 500, :json => {}
   end
  end
 end
jQuery: success!
  create_comment: function(comment) {
      $.ajax({
            …
            success: function(result) {
                 $('#new_comment').hide();
                 //feedback to communicate success
            },
            error: function(xhr, status, error) {
                 //feedback to communicate error
            }
      });
  }
Interchange
 User           jQuery             ActionMap             Perl Module
              ActionMap will route URL to desired
              functionality.                               HTML

   jQuery     Perl Module will set mv_nextpage and set
              Scratch variables.
                                                           jQuery
   JSON       Perl Module can use JSON module to set
              Scratch variable to JSON-ified data.

Perl Module          ActionMap              jQuery          User
Pagination
                   respond_to do |format|
                    format.html do
                     if request.xhr?                       success:function() {
                         render :partial => 'item_block'       //replace HTML
dataType: “html”
                     else                                      //apply listeners
                         render 'index'                        //replace pagination
                     end                                   }
                    end
                   end
.js & js.erb
It's worth noting that you can also return JavaScript or JavaScript from
a js.erb file as a Rails controller response. erb is a templating language.
The resulting JavaScript will be executed by jQuery.

            respond_to do |format|
             format.js { render :text => "alert('hello')" }
            end

I prefer returning JSON, because I've seen this be finicky and it can be
difficult to debug.
JSON
      jQuery and JavaScript                                  Rails


var obj = $.parseJSON(string);              render :json => comment

//parse a string into a JSON object         # automatically calls to_json


JSON.stringify(obj);                        to_json

//stringify a JSON object into JSON         # converts objects to string

//text for use as argument string           # arguments: only, except, include
                                            # nested resources


        http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html
data tag & HTML5
                       Rails
 <div id=“comment” data-id=“<%= comment.id %>”>
 </div>

                       jQuery

          $('.comment').data('id');
          $('.comment').data('id', 123);
          $('.comment').removeData('id');



                 everything in moderation.
The Future
User         jQuery              Controller       HTML


                                                  jQuery

  What if you want to skip the
  first AJAX call for performance?
                                                   User



 jQuery           JSON               Controller   jQuery
The Future
                   Options for eliminating first AJAX call

●   Render HTML form inline (once)

●   Render HTML form in JavaScript with jQuery HTML builder nodes

●   Use a template system like Mustache.js or Handlebars.js

●   Use a JavaScript [client-side] Model-View framework like
    Backbone.js
Mustache.js
                                                                                 Edit
     { }
var comment_template = “<h3>{{header}}</h3>
                                                        var comment = {
                                                             header: “Edit your Comment!”,
                                                             title: “Awesome”,
                                                             data: “This is an awesome photo.”
<p class=“error”></p>
                                                        };
<label for=“title”>Title</label>
                                                        $.mustache(comment_template, comment);
<input type=“text” name=“title” value=“{{title}}” />
<label for=“data”>Data</label>
<textarea name=“data”>{{data}}</textarea>                                       New
<input type=“submit” value= “submit” />”;               var comment = {
                                                             header: “Comment on This!”
                                                        };
                                                        $.mustache(comment_template, comment);


                                     http://mustache.github.com/
Disclaimer

●   Other modern javascript frameworks
    have much of the same functionality
    here, specifically YUI. You have a choice.




        http://developer.yahoo.com/yui/
jQuery & Rails
●   jQuery and Rails work together to
    write rich web applications.

●   jQuery is most popular and known for
    it's conciseness and readability, and
    unique “chaining” method

●   DIG into the documentation. jQuery
    and Ruby documentation is good.
    Rails is “up and coming”.

          http://visualjquery.com/
Photo Credits



●   http://www.etsy.com/listing/62497842/eloise-and-ramona-play-telephone-best
●   me: http://www.flickr.com/photos/just_steph/
Questions?

More Related Content

What's hot

Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBApaichon Punopas
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - IntroductionSagar Acharya
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSVisual Engineering
 
AngularJS for Java Developers
AngularJS for Java DevelopersAngularJS for Java Developers
AngularJS for Java DevelopersLoc Nguyen
 
AtlasCamp 2015: Web technologies you should be using now
AtlasCamp 2015: Web technologies you should be using nowAtlasCamp 2015: Web technologies you should be using now
AtlasCamp 2015: Web technologies you should be using nowAtlassian
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingBinary Studio
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPressCaldera Labs
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJSWei Ru
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JSAkshay Mathur
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux IntroductionNikolaus Graf
 
React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)
React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)
React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)Binary Studio
 
Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseEPAM Systems
 
AtlasCamp 2015: Using add-ons to build add-ons
AtlasCamp 2015: Using add-ons to build add-onsAtlasCamp 2015: Using add-ons to build add-ons
AtlasCamp 2015: Using add-ons to build add-onsAtlassian
 
AngularJS intro
AngularJS introAngularJS intro
AngularJS introdizabl
 
AngularJS Beginners Workshop
AngularJS Beginners WorkshopAngularJS Beginners Workshop
AngularJS Beginners WorkshopSathish VJ
 

What's hot (20)

Dynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDBDynamic Application Development by NodeJS ,AngularJS with OrientDB
Dynamic Application Development by NodeJS ,AngularJS with OrientDB
 
Angular JS - Introduction
Angular JS - IntroductionAngular JS - Introduction
Angular JS - Introduction
 
Angular js
Angular jsAngular js
Angular js
 
React js
React jsReact js
React js
 
Workshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJSWorkshop 27: Isomorphic web apps with ReactJS
Workshop 27: Isomorphic web apps with ReactJS
 
AngularJS Best Practices
AngularJS Best PracticesAngularJS Best Practices
AngularJS Best Practices
 
Angular JS
Angular JSAngular JS
Angular JS
 
AngularJS for Java Developers
AngularJS for Java DevelopersAngularJS for Java Developers
AngularJS for Java Developers
 
AtlasCamp 2015: Web technologies you should be using now
AtlasCamp 2015: Web technologies you should be using nowAtlasCamp 2015: Web technologies you should be using now
AtlasCamp 2015: Web technologies you should be using now
 
Academy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & ToolingAcademy PRO: React JS. Redux & Tooling
Academy PRO: React JS. Redux & Tooling
 
Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Introduction to AJAX In WordPress
Introduction to AJAX In WordPressIntroduction to AJAX In WordPress
Introduction to AJAX In WordPress
 
Practical AngularJS
Practical AngularJSPractical AngularJS
Practical AngularJS
 
Getting Started with Angular JS
Getting Started with Angular JSGetting Started with Angular JS
Getting Started with Angular JS
 
React + Redux Introduction
React + Redux IntroductionReact + Redux Introduction
React + Redux Introduction
 
React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)
React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)
React vs Angular: ups & downs (speaker Oleksandr Kovalov, Binary Studio)
 
Angular Js Get Started - Complete Course
Angular Js Get Started - Complete CourseAngular Js Get Started - Complete Course
Angular Js Get Started - Complete Course
 
AtlasCamp 2015: Using add-ons to build add-ons
AtlasCamp 2015: Using add-ons to build add-onsAtlasCamp 2015: Using add-ons to build add-ons
AtlasCamp 2015: Using add-ons to build add-ons
 
AngularJS intro
AngularJS introAngularJS intro
AngularJS intro
 
AngularJS Beginners Workshop
AngularJS Beginners WorkshopAngularJS Beginners Workshop
AngularJS Beginners Workshop
 

Viewers also liked

Let's Learn Ruby - Basic
Let's Learn Ruby - BasicLet's Learn Ruby - Basic
Let's Learn Ruby - BasicEddie Kao
 
Swift distributed tracing method and tools v2
Swift distributed tracing method and tools v2Swift distributed tracing method and tools v2
Swift distributed tracing method and tools v2zhang hua
 
Action Controller Overview, Season 1
Action Controller Overview, Season 1Action Controller Overview, Season 1
Action Controller Overview, Season 1RORLAB
 
Control review for iOS
Control review for iOSControl review for iOS
Control review for iOSWilliam Price
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with RspecBunlong Van
 
jQuery For Beginners - jQuery Conference 2009
jQuery For Beginners - jQuery Conference 2009jQuery For Beginners - jQuery Conference 2009
jQuery For Beginners - jQuery Conference 2009Ralph Whitbeck
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutesSimon Willison
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to SwiftGiordano Scalzo
 
Introduction to html
Introduction to htmlIntroduction to html
Introduction to htmlvikasgaur31
 
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web ArchitectureChamnap Chhorn
 
Learn OpenStack from trystack.cn
Learn OpenStack from trystack.cnLearn OpenStack from trystack.cn
Learn OpenStack from trystack.cnOpenCity Community
 
Reunió d'aula 4t B Curs 2014-15 Escola Consol Ferré
Reunió d'aula 4t B Curs 2014-15 Escola Consol FerréReunió d'aula 4t B Curs 2014-15 Escola Consol Ferré
Reunió d'aula 4t B Curs 2014-15 Escola Consol Ferréangiarrufat
 
I made my blog my business
I made my blog my businessI made my blog my business
I made my blog my businessBrian Krogsgard
 
SafePeak - How to configure SQL Server agent in a safepeak deployment
SafePeak - How to configure SQL Server agent in a safepeak deploymentSafePeak - How to configure SQL Server agent in a safepeak deployment
SafePeak - How to configure SQL Server agent in a safepeak deploymentVladi Vexler
 
Faithful stewardship -sld 2011, final
Faithful stewardship -sld 2011, finalFaithful stewardship -sld 2011, final
Faithful stewardship -sld 2011, finalLaurel Amabile
 

Viewers also liked (20)

Let's Learn Ruby - Basic
Let's Learn Ruby - BasicLet's Learn Ruby - Basic
Let's Learn Ruby - Basic
 
Swift distributed tracing method and tools v2
Swift distributed tracing method and tools v2Swift distributed tracing method and tools v2
Swift distributed tracing method and tools v2
 
Action Controller Overview, Season 1
Action Controller Overview, Season 1Action Controller Overview, Season 1
Action Controller Overview, Season 1
 
Control review for iOS
Control review for iOSControl review for iOS
Control review for iOS
 
September2011aftma
September2011aftmaSeptember2011aftma
September2011aftma
 
Ruby on Rails testing with Rspec
Ruby on Rails testing with RspecRuby on Rails testing with Rspec
Ruby on Rails testing with Rspec
 
jQuery For Beginners - jQuery Conference 2009
jQuery For Beginners - jQuery Conference 2009jQuery For Beginners - jQuery Conference 2009
jQuery For Beginners - jQuery Conference 2009
 
Learning jQuery in 30 minutes
Learning jQuery in 30 minutesLearning jQuery in 30 minutes
Learning jQuery in 30 minutes
 
A swift introduction to Swift
A swift introduction to SwiftA swift introduction to Swift
A swift introduction to Swift
 
Web application architecture
Web application architectureWeb application architecture
Web application architecture
 
Introduction to html
Introduction to htmlIntroduction to html
Introduction to html
 
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho PolutaInfinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
 
Introduction to Web Architecture
Introduction to Web ArchitectureIntroduction to Web Architecture
Introduction to Web Architecture
 
4. η θεια λειτουργια των πιστων
4.  η θεια λειτουργια των πιστων4.  η θεια λειτουργια των πιστων
4. η θεια λειτουργια των πιστων
 
Learn OpenStack from trystack.cn
Learn OpenStack from trystack.cnLearn OpenStack from trystack.cn
Learn OpenStack from trystack.cn
 
Reunió d'aula 4t B Curs 2014-15 Escola Consol Ferré
Reunió d'aula 4t B Curs 2014-15 Escola Consol FerréReunió d'aula 4t B Curs 2014-15 Escola Consol Ferré
Reunió d'aula 4t B Curs 2014-15 Escola Consol Ferré
 
Band of sounds
Band of soundsBand of sounds
Band of sounds
 
I made my blog my business
I made my blog my businessI made my blog my business
I made my blog my business
 
SafePeak - How to configure SQL Server agent in a safepeak deployment
SafePeak - How to configure SQL Server agent in a safepeak deploymentSafePeak - How to configure SQL Server agent in a safepeak deployment
SafePeak - How to configure SQL Server agent in a safepeak deployment
 
Faithful stewardship -sld 2011, final
Faithful stewardship -sld 2011, finalFaithful stewardship -sld 2011, final
Faithful stewardship -sld 2011, final
 

Similar to jQuery and Rails: Best Friends Forever

Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for JoomlaLuke Summerfield
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJSAaronius
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascriptAlmog Baku
 
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
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejsNick Lee
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascriptaglemann
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011Arun Gupta
 
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
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Libraryrsnarayanan
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationAndrew Rota
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksHjörtur Hilmarsson
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Treeadamlogic
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajaxbaygross
 
Academy PRO: React JS
Academy PRO: React JSAcademy PRO: React JS
Academy PRO: React JSBinary Studio
 
Working with Javascript in Rails
Working with Javascript in RailsWorking with Javascript in Rails
Working with Javascript in RailsSeungkyun Nam
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...SPTechCon
 

Similar to jQuery and Rails: Best Friends Forever (20)

Rails is not just Ruby
Rails is not just RubyRails is not just Ruby
Rails is not just Ruby
 
Javascript Frameworks for Joomla
Javascript Frameworks for JoomlaJavascript Frameworks for Joomla
Javascript Frameworks for Joomla
 
Dependency Management with RequireJS
Dependency Management with RequireJSDependency Management with RequireJS
Dependency Management with RequireJS
 
Drupal & javascript
Drupal & javascriptDrupal & javascript
Drupal & javascript
 
Introduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress DevelopersIntroduction to AngularJS For WordPress Developers
Introduction to AngularJS For WordPress Developers
 
Jquery 4
Jquery 4Jquery 4
Jquery 4
 
JQuery In Drupal
JQuery In DrupalJQuery In Drupal
JQuery In Drupal
 
Understanding backbonejs
Understanding backbonejsUnderstanding backbonejs
Understanding backbonejs
 
Beyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance JavascriptBeyond DOMReady: Ultra High-Performance Javascript
Beyond DOMReady: Ultra High-Performance Javascript
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011
 
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
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
 
Integrating React.js Into a PHP Application
Integrating React.js Into a PHP ApplicationIntegrating React.js Into a PHP Application
Integrating React.js Into a PHP Application
 
Javascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & TricksJavascript MVC & Backbone Tips & Tricks
Javascript MVC & Backbone Tips & Tricks
 
JS-05-Handlebars.ppt
JS-05-Handlebars.pptJS-05-Handlebars.ppt
JS-05-Handlebars.ppt
 
jQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a TreejQuery and Rails, Sitting in a Tree
jQuery and Rails, Sitting in a Tree
 
Week 4 - jQuery + Ajax
Week 4 - jQuery + AjaxWeek 4 - jQuery + Ajax
Week 4 - jQuery + Ajax
 
Academy PRO: React JS
Academy PRO: React JSAcademy PRO: React JS
Academy PRO: React JS
 
Working with Javascript in Rails
Working with Javascript in RailsWorking with Javascript in Rails
Working with Javascript in Rails
 
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
The Magic Revealed: Four Real-World Examples of Using the Client Object Model...
 

Recently uploaded

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
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
 
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
 
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
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demoHarshalMandlekar2
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 

Recently uploaded (20)

WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
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
 
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
 
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
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
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
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Sample pptx for embedding into website for demo
Sample pptx for embedding into website for demoSample pptx for embedding into website for demo
Sample pptx for embedding into website for demo
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
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!
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 

jQuery and Rails: Best Friends Forever

  • 1. jQuery & Rails Best Friends Forever* Best Friends Forever* *Forever as used by a 6th-grader *Forever in the sense of a sixth grader.
  • 2. I'll Cover: ● Brief Rails explanation ● Brief jQuery explanation ● Nice methods between each technology to encourage a rich web app ● AJAX ● JSON ● data ● The Future
  • 3. jQuery... ● is a JavaScript framework (YUI, prototype, scriptaculous) ● includes basic JavaScript functionality for AJAX, DOM manipulation, events ● likes to hang out with jQuery UI, user interface library, interactions, widgets, effects, themes ● is known for being concise and readable http://jqueryui.com/
  • 5. Ruby on Rails... ● is a MVC framework built on Ruby ● is a tool for efficient development that follows universal conventions ● is designed to work well with JavaScript + AJAX
  • 6. AJAX in jQuery $.ajax({ url: "test.html", data: $('#form').serialize(), type: “POST”, cache: false, dataType: “html”, success: function(){ //do something }, error: function() { //do something else } }); http://api.jquery.com/jQuery.ajax/
  • 7. Rails Tidbits ● Routing: connects URLs to Code match “/products/:id” => “products#show” ● Handling different responses respond_to do |format| format.html format.xml { … } end ● Handling JSON response respond_to do |format| format.json { render :json => data } end
  • 8. Rails Tidbits ● Request object request.xhr? ● Handling CGI parameters params[:name], params[:description] params.has_key?(:name) p = Product.new(params[:product]) p.save # check for p.errors product.update_attributes(params[:product])
  • 10. User: Initiates Action //jQuery wrapper method $.fn.comment_photo = function() { //do stuff } $(function() { $('.comment-photo').click(function() { $(this).comment_photo(); }); })
  • 11. jQuery: AJAX call $.fn.comment_photo = function() { $.ajax({ url: “/comment/new", data: { photo_id: this.attr('id') }, cache: false, dataType: “html” … }); }
  • 12. Rails: calls Controller class CommentsController < ApplicationController def new @comment = Comment.new respond_to do |format| format.html #new.html.erb end end end
  • 13. Rails: renders HTML erb HTML <% form_for @comment do |f| %> <form action= “/comments” method=”post”> <%= f.label :title %> <label for=“comment_title”>Title</label> <%= f.text_field :title %> <input type=“text” id=“comment_title” name=“comment[title]” /> <%= f.label :data %> <label for=“comment_data”>Data</label> <%= f.text_area :data %> <textarea id=“comment_data” name=“comment[data]” /></textarea> <%= f.submit %> <input type=“submit” id=“comment_submit” value=”Create ” /> <% end %> </form> http://www.ruby-doc.org/stdlib/libdoc/erb/rdoc/
  • 14. jQuery: displays HTML $.fn.comment_photo = function() { $.ajax({ … success: function(html) { $('#new_comment').html(html); } }); }
  • 15. User: more action //extending jQuery object $.extend({ create_comment: function(form) { //do stuff } }); $(function() { $('#new_comment').submit(function() { $.create_comment($(this)); }); })
  • 16. jQuery: AJAX call create_comment: function(form) { $.ajax({ url: form.attr('action'), type: “POST”, data: { comment: form.serialize() }, cache: false, dataType: “JSON” … }); }
  • 17. Rails: calls Controller class CommentsController < ApplicationController def create begin comment = Comment.new(params[:comment]) comment.user = current_user comment.save respond_to do |format| format.json :json => comment end rescue Exception => e render :status => 500, :json => {} end end end
  • 18. jQuery: success! create_comment: function(comment) { $.ajax({ … success: function(result) { $('#new_comment').hide(); //feedback to communicate success }, error: function(xhr, status, error) { //feedback to communicate error } }); }
  • 19. Interchange User jQuery ActionMap Perl Module ActionMap will route URL to desired functionality. HTML jQuery Perl Module will set mv_nextpage and set Scratch variables. jQuery JSON Perl Module can use JSON module to set Scratch variable to JSON-ified data. Perl Module ActionMap jQuery User
  • 20. Pagination respond_to do |format| format.html do if request.xhr? success:function() { render :partial => 'item_block' //replace HTML dataType: “html” else //apply listeners render 'index' //replace pagination end } end end
  • 21. .js & js.erb It's worth noting that you can also return JavaScript or JavaScript from a js.erb file as a Rails controller response. erb is a templating language. The resulting JavaScript will be executed by jQuery. respond_to do |format| format.js { render :text => "alert('hello')" } end I prefer returning JSON, because I've seen this be finicky and it can be difficult to debug.
  • 22. JSON jQuery and JavaScript Rails var obj = $.parseJSON(string); render :json => comment //parse a string into a JSON object # automatically calls to_json JSON.stringify(obj); to_json //stringify a JSON object into JSON # converts objects to string //text for use as argument string # arguments: only, except, include # nested resources http://api.rubyonrails.org/classes/ActiveRecord/Serialization.html
  • 23. data tag & HTML5 Rails <div id=“comment” data-id=“<%= comment.id %>”> </div> jQuery $('.comment').data('id'); $('.comment').data('id', 123); $('.comment').removeData('id'); everything in moderation.
  • 24. The Future User jQuery Controller HTML jQuery What if you want to skip the first AJAX call for performance? User jQuery JSON Controller jQuery
  • 25. The Future Options for eliminating first AJAX call ● Render HTML form inline (once) ● Render HTML form in JavaScript with jQuery HTML builder nodes ● Use a template system like Mustache.js or Handlebars.js ● Use a JavaScript [client-side] Model-View framework like Backbone.js
  • 26. Mustache.js Edit { } var comment_template = “<h3>{{header}}</h3> var comment = { header: “Edit your Comment!”, title: “Awesome”, data: “This is an awesome photo.” <p class=“error”></p> }; <label for=“title”>Title</label> $.mustache(comment_template, comment); <input type=“text” name=“title” value=“{{title}}” /> <label for=“data”>Data</label> <textarea name=“data”>{{data}}</textarea> New <input type=“submit” value= “submit” />”; var comment = { header: “Comment on This!” }; $.mustache(comment_template, comment); http://mustache.github.com/
  • 27. Disclaimer ● Other modern javascript frameworks have much of the same functionality here, specifically YUI. You have a choice. http://developer.yahoo.com/yui/
  • 28. jQuery & Rails ● jQuery and Rails work together to write rich web applications. ● jQuery is most popular and known for it's conciseness and readability, and unique “chaining” method ● DIG into the documentation. jQuery and Ruby documentation is good. Rails is “up and coming”. http://visualjquery.com/
  • 29. Photo Credits ● http://www.etsy.com/listing/62497842/eloise-and-ramona-play-telephone-best ● me: http://www.flickr.com/photos/just_steph/

Editor's Notes

  1. Also known for it&apos;s chaining model
  2. - 360k sites use jQuery, as compared to 55k MooTools, 39k Prototype, 30k YUI, 9k script.aculo.us - 66% of web page visits use jQuery
  3. - what are the bare minimum, step by step - context, onstart, tons of arguments
  4. - routing is akin to Interchange actionmaps (although evolved, more complex) - rendering :json automaticallly calls a to_json method on the data
  5. - the request object contains a lot of useful information about the request: host, domain, format, method, type of request, headers, port, protocol, etc.
  6. ParseJSON is a jQuery specific function, while JSON.stringify is not a part of the jQuery library (JSON also has it&apos;s own parse method). to_json nested elements might include images belonging to product
  7. - only works in HTML5 - in addition to id, you may also want to track nested ids, or other information about that comment that has little to do with CSS styles - jQuery has getter and setter methods here, for data - e.g. of use: multiple comments on one page, but HTML for one form. When click on edit comment, data is set to identify which comment is being edited.
  8. - writing your own HTML can be messy, but give you full control - using a template system encourages DRY - using a client side model-view paradigm may result in reproducing business logic for an individual model (that business logic also lives on the server side) - disadvantage to all: you aren&apos;t leveraging server side functionality or helpers for building Rails forms - advantage to all: speed, less dependency on server for AJAX hits