jQuery : Talk to server with Ajax
Upcoming SlideShare
Loading in...5
×
 

jQuery : Talk to server with Ajax

on

  • 6,208 views

 

Statistics

Views

Total Views
6,208
Views on SlideShare
6,176
Embed Views
32

Actions

Likes
0
Downloads
83
Comments
0

3 Embeds 32

http://wildanm.wordpress.com 17
http://www.slideshare.net 14
http://74.125.47.132 1

Accessibility

Categories

Upload Details

Uploaded via as OpenOffice

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

    jQuery : Talk to server with Ajax jQuery : Talk to server with Ajax Presentation Transcript

    • Wildan Maulana | wildan [at] tobethink.com #8 jQuery: Talk to the server with Ajax Doc. v. 0.1 - 10/03/09
    • This Presentation Cover
      • A brief overview of Ajax
      • Loading pre-formatted HTML from the server
      • Making general GET and POST requests
      • Making requests with fine-grained control
      • Setting default ajax properties
      • A comprehensive example
    • A brief overview of Ajax
      • TODO
    • Brusing up an Ajax
      • TODO
    • Creating an XHR instance if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject("Msxml2.XMLHTTP"); } else { throw new Error("Ajax is not supported by this browser"); }
    • XHR Methods and Properties Methods Description abort() Causes the currently executing request to be cancelled getAllResponseHeaders() Returns a single string containing the names and values of all response headers open(method, url, async, username, password) Return the value of the named response header send(content) Initiates the requests with the specified (optional) body content setRequestHeader(name, value) Sets a request header using the specified name and value
    • XHR Methods and Properties Methods Description onreadystatechange Assigns the event handler used when the state of the requests change readyState
        An integer value that indicates the state of the request as follows :
      • 0 – Uninitialized
      • 1 – Loading
      • 2 – Loaded
      • 3 – Interactive
      • 4 - Complete
      responseText The body content returned in the response responseXML If the body content is XML, the XML DOM created from the body content status Responses status code returned from the server. For example : 200 for success or 404 for not found statusText The status text message returned by the response
    • Initiating the Request
      • Before we can send a request to the server, we need to do the following setup steps :
        • Specify the HTTP method such as (POST or GET)
        • Provide the URL of the server-side resource to be contacted
        • Let the XHR instance know how it can inform us of its progress
        • Provide any body content for the POST request
      xhr.open('GET','/some/resource/url'); -> step 1 and 2 xhr.send(null); -> step 4 if get xhr.send('a=1&b=2&c=3'); -> step 4 if post
    • Keeping track of progress
      • An XHR instance informs us of its progress through the ready state handler. This handler is established by assigning a reference to the function to serve as the ready handler to the onreadystatechange property of the XHR instance.
      xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300) { //success } else { //error } } } Ignores all but cempleted state Branches on responses status Executes on success Executes on failure
    • Getting the response
      • TODO
    • The lifecycle of an Ajax
    • Pain Points that page authors using Ajax need to deal with
      • Instantiating an XHR object requires browser-specific code.
      • Ready handlers need to sift through a lot of uninteresting state changes.
      • Ready handlers don’t automatically get a reference to invoking XHR
      • instances.
      • The response body needs to be dealt with in numerous ways depending
      • upon its format.
    • Loading Content into elements
      • Let's imagine that, on page load, we want to grab a chunk of HTML from the server using a resource named /serverResource
      var xhr; if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject(&quot;Msxml2.XMLHTTP&quot;); } else { throw new Error(&quot;Ajax is not supported by this browser&quot;); } xhr.onreadystatechange = function() { if (xhr.readyState == 4) { if (xhr.status >= 200 && xhr.status < 300) { document.getElementById('someContainer') .innerHTML = xhr.responseText; } } } xhr.open('GET','/serverResource'); xhr.send();
    •  
    • Loading Content with jQuery
      • On jQuery we can use : $('#someContainer').load('/serverResource');
      load(url, parameters, callback) Initiates an Ajax request to the specified URL with optional parameters. A callback function can be specified that’s invoked when the request completes. The response text replaces the content of all matched elements. Parameters url (String) The URL of the server-side resource to which the request is sent. parameters (Object) An object whose properties are serialized into properly encoded parameters to be passed to the request. If specified, the request is made using the POST method. If omitted, the GET method is used. callback (Function) A callback function invoked after the response data has been loaded into the elements of the matched set. The parameters passed to this function are the response text, the status code, and the XHR instance. Returns The wrapped set
    • Filtering Response
      • If we want to filter response elements, jQuery allows us to specify a selector on the URL that will be used to limit which response elements are injected into the wrapped elements by suffixing the URL with a space and pound sign character (#) followed
      • by the selector.
      • For example, to filter response elements so that only <div> instances are injected, we write :
        • $('.injectMe').load('/someResource #div');
    • If the Request come from form control serialize() Creates a properly formatted and encoded query string from all successful form elements in the wrapped set. Parameters none Returns The formatted query string The serialize() method gather data in a query string, if we want get data in a JavaScript array, jQuery provides serializeArray() method described next ...
    • Get the form data in a JavaScript array serializeArray() Collects the values of all successful form controls into an array of objects containing the names and values of the controls Parameters none Returns The formatted query string
    • Loading dynamic inventory data
    • The HTML Markup <body id=&quot;bootCloset1&quot;> <img id=&quot;banner&quot; src=&quot;boot.closet.branding.png&quot;/> <form action=&quot;&quot; id=&quot;orderForm&quot;> <div id=&quot;detailFormContainer&quot;> <h1>Choose your boots</h1> <div> <label>Please choose a style:</label><br/> <select id=&quot;styleDropdown&quot;> <option value=&quot;&quot;>Please choose a boot style</option> <option value=&quot;7177382&quot;>Caterpillar Tradesman Work Boot</option> <option value=&quot;7269643&quot;>Caterpillar Logger Boot</option> <option value=&quot;7141832&quot;>Chippewa 17&quot; Engineer Boot</option> <option value=&quot;7141833&quot;>Chippewa 17&quot; Snakeproof Boot</option> <option value=&quot;7173656&quot;>Chippewa 11&quot; Engineer Boot</option> <option value=&quot;7141922&quot;>Chippewa Harness Boot</option> <option value=&quot;7141730&quot;>Danner Foreman Pro Work Boot</option> <option value=&quot;7257914&quot;>Danner Grouse GTX Boot</option> </select> </div> <div id=&quot;detailsDisplay&quot;></div> </div> </form> </body> s Empty <div>
    • JQuery in Action $(function(){ $('#styleDropdown') .change(function(){ var styleValue = $(this).val(); $('#detailsDisplay').load( 'getDetails.jsp', { style: styleValue } ); }) .change(); }); Wraps style dropdown and binds change handler Loads data for selected style Trigers change handler
    • The server-side resource returns a pre-formatted fragment of HTML to display the boot information.
    • Making GET and POST requests
      • The intentions of GET and POST requests :
        • GET requests—Intended to be idempotent; the state of the server and the model data for the application should be unaffected by a GET operation. The same GET operation, made again and again and again, should return exactly the same results (assuming no other force is at work changing the server state).
        • POST requests—Can be non-idempotent; the data they send to the server can be used to change the model state of the application; for example, adding records to a database or removing information from the server.
    • Getting data with jQuery $.get(url,parameters,callback)
        Initiates a GET request to the server using the specified URL with any passed parameters as the query string.
      Parameters url (String) The URL of the server-side resource to contact via the GET method. parameters (Object|String) An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string. callback (Function) A function invoked when the request completes. The response callback body is passed as the first parameter to this callback, and the status as the second. Returns The XHR instance
    • $.get() example <html> <head> <title>$.get() Example</title> <link rel=&quot;stylesheet&quot; type=&quot;text/css&quot; href=&quot;../common.css&quot;> <script type=&quot;text/javascript&quot; src=&quot;../scripts/jquery-1.2.1.js&quot;></script> <script type=&quot;text/javascript&quot;> $(function(){ $('#testButton').click(function(){ $.get( 'reflectData.jsp', {a:1, b:2, c:3}, function(data) { alert(data); } ); }); }); </script> </head> <body> <button type=&quot;button&quot; id=&quot;testButton&quot;> Click me!</button> </body> </html> Gets data from server
    • Getting JSON data : $.getJSON $.get(url,parameters,callback)
      • Initiates a GET request to the server using the specified URL with any passed parameters as the query string. The response is interpreted as a JSON string, and the resulting data is passed to the callback function.
      Parameters url (String) The URL of the server-side resource to contact via the GET method. parameters (Object|String) An object whose properties serve as the name/value pairs used to construct a query string to be appended to the URL, or a preformatted and encoded query string. callback (Function) A function invoked when the request completes. The data value resulting from digesting the response body as a JSON string is passed as the first parameter to this callback, and the status as the second. Returns The XHR instance
    • Loading cascading dropdowns The initial state of the order form with the dependent dropdowns in an empty and disabled state
    • <body id=&quot; bootCloset2 &quot;> <img id=&quot;banner&quot; src=&quot;boot.closet.branding.png&quot;/> <form action=&quot;&quot; id=&quot;orderForm&quot;> <div id=&quot;detailFormContainer&quot;> <h1>Choose your boots</h1> <div id=&quot;cascadingDropdowns&quot;> <div> <label>Please choose a style:</label><br/> <select id=&quot;styleDropdown&quot;> <option value=&quot;&quot;>Please choose a boot style</option> <option value=&quot;7177382&quot;> Caterpillar Tradesman Work Boot</option> <option value=&quot;7269643&quot;>Caterpillar Logger Boot</option> <option value=&quot;7141832&quot;>Chippewa 17&quot; Engineer Boot</option> <option value=&quot;7141833&quot;>Chippewa 17&quot; Snakeproof Boot</option> <option value=&quot;7173656&quot;>Chippewa 11&quot; Engineer Boot</option> <option value=&quot;7141922&quot;>Chippewa Harness Boot</option> <option value=&quot;7141730&quot;>Danner Foreman Pro Work Boot</option> <option value=&quot;7257914&quot;>Danner Grouse GTX Boot</option> </select> </div> <div> <label>Color:</label><br/> <select id=&quot;colorDropdown&quot; disabled=&quot;disabled&quot;></select> </div> <div> <label>Size:</label><br/> <select id=&quot;sizeDropdown&quot; disabled=&quot;disabled&quot;></select> </div> </div> <div id=&quot;detailsDisplay&quot;></div> </div> </form> </body>
    • The New Ready Handler $(function(){ $('#styleDropdown') .change(function(){ var styleValue = $(this).val(); $('#detailsDisplay').load( 'getDetails.jsp', { style: styleValue } ); adjustColorDropdown(); }) .change(); $('#colorDropdown') .change(adjustSizeDropdown); }); Triggers state adjusments of color dropdown
    • adjustColorDropdown() [ {value:'',caption:'choose color'}, {value:'bk',caption:'Black Oil-tanned'}, {value:'br',caption:'Black Polishable'} ] function adjustColorDropdown() { var styleValue = $('#styleDropdown').val(); var dropdownSet = $('#colorDropdown'); if (styleValue.length == 0) { dropdownSet.attr(&quot;disabled&quot;,true); $(dropdownSet).emptySelect(); adjustSizeDropdown(); } else { dropdownSet.attr(&quot;disabled&quot;,false); $.getJSON( 'getColors.jsp', {style:styleValue}, function(data){ $(dropdownSet).loadSelect(data); adjustSizeDropdown(); } ); } } Enables or disables the color dropdown Empties disabled dropdown and clears dependent drop down Gets color values based on style Triggers adjusments of dependent dropdown We will create this function later .. @_@ A typical JSON construct returned from getColors.jsp
    • adjustSizeDropdown() function adjustSizeDropdown() { var styleValue = $('#styleDropdown').val(); var colorValue = $('#colorDropdown').val(); var dropdownSet = $('#sizeDropdown'); if ((styleValue.length == 0)||(colorValue.length == 0) ) { dropdownSet.attr(&quot;disabled&quot;,true); $(dropdownSet).emptySelect(); }else { dropdownSet.attr(&quot;disabled&quot;,false); $.getJSON( 'getSizes.jsp', {style:styleValue,color:colorValue}, function(data){$(dropdownSet).loadSelect(data)} ); } }
    • The Results
    • Writing the custom commands emptySelect() : $.fn.emptySelect = function() { return this.each(function(){ if (this.tagName=='SELECT') this.options.length = 0; }); } loadSelect() : $.fn.loadSelect = function(optionsDataArray) { return this.emptySelect().each(function(){ if (this.tagName=='SELECT') { var selectElement = this; $.each(optionsDataArray,function(index,optionData){ var option = new Option(optionData.caption, optionData.value); if ($.browser.msie) { selectElement.add(option); } else { selectElement.add(option,null); } }); } }); }
    • The Implementation of our custom select command (function($) { $.fn.emptySelect = function() { return this.each(function(){ if (this.tagName=='SELECT') this.options.length = 0; }); } $.fn.loadSelect = function(optionsDataArray) { return this.emptySelect().each(function(){ if (this.tagName=='SELECT') { var selectElement = this; $.each(optionsDataArray,function(index,optionData){ var option = new Option(optionData.caption, optionData.value); if ($.browser.msie) { selectElement.add(option); } else { selectElement.add(option,null); } }); } }); } })(jQuery);
    • GET is not enough ! Between $.get() and $.getJSON() , jQuery gives us some powerful tools when it comes to making GET requests, but man does not live by GETs alone!
    • Making POST request : $.post $.post(url,parameters,callback)
        Initiates a POST request to the server using the specified URL with any parameters passed within the body of the request.
      Parameters url (String) The URL of the server-side resource to contact via the POST method. parameters (Object|String) An object whose properties serve as the name/value pairs parameters used to construct the body of the request, or a preformatted and encoded query string. callback
        (Function) A function invoked when the request completes. The response callback body is passed as the single parameter to this callback, and the status as the second.
      Returns The XHR instance
    • Taking full control of an Ajax request
      • The functions and commands that we’ve seen so far are convenient for many cases, but there may be times when we want to take control of the nitty-gritty details into our own hands.
    • Making Ajax requests with all the trimmings
      • For those times when we want or need to exert a fine-grained level of control over how we make Ajax requests, jQuery provides a general utility function for making Ajax requests named $.ajax()
      • Under the covers, all other jQuery features that make Ajax requests eventually use this function to initiate the request
      Command syntax : $.ajax $.ajax(options) Initiates an Ajax request using the passed options to control how the request is made and callbacks notified. Parameters options (Object) An object instance whose properties define the parameters to this operation. See next slide for details. Returns The XHR instance.
    • Options for the $.ajax() utility function Name Type Utility url String The URL for the request type String The HTTP method to use. Usually either POST or GET. If omitted, the defaultis GET. data Object An object whose properties serve as the query parameters to be passed to the request. If the request is a GET, this data is passed as the query string. If a POST, the data is passed as the request body. In either case, the encoding of the values is handled by the $.ajax() utility function.
    • Options for the $.ajax() utility function Name Type Utility dataType String A keyword that identifies the type of data that’s expected to be returned by the response. This value determines what, if any, post-processing occurs upon the data before being passed to callback functions. The valid values are as follows:
      • xml—The response text is parsed as an XML document and the resulting XML DOM is passed to the callbacks.
      • html—The response text is passed unprocessed to the callbacks functions. Any <script> blocks within the returned HTML fragment are evaluated.
      • json—The response text is evaluated as a JSON string, and the resulting object is passed to the callbacks.
      • jsonp—Similar to json except that remote scripting is allowed,assuming the remote server supports it.
      • script—The response text is passed to the callbacks. Prior to any callbacks being invoked, the response is processed as a JavaScript statement or statements.
      • text—The response text is assumed to be plain text.The server resource is responsible for setting the appropriate content-type response header. If this property is omitted, the response text is passed to the callbacks with-out any processing or evaluation.
    • Options for the $.ajax() utility function Name Type Utility timeout Number Sets a timeout for the Ajax request in milliseconds. If the request does not complete before the timeout expires, the request is aborted and the error callback (if defined) is called. global Boolean
        Enables (if true) or disables (if false) the triggering of so-called global functions. These are functions that can be attached to elements that trigger at various points or conditions during an Ajax call. We’ll be discussing them in detail in section 8.8. If omitted, the default is to enable the triggering of global functions.
      contentType String
        The content type to be specified on the request. If omitted, the default is contentType application/x-www-form-urlencoded, the same type used as the default for form submissions.
    • Options for the $.ajax() utility function Name Type Utility
        success
      Function A function invoked if the response to the request indicates a success status code. The response body is returned as the first parameter to this function and formatted according to the specification of the dataType property. The second parameter is a string containing a status value—in this case,always success. error Function A function invoked if the response to the request returns an error status code. Three arguments are passed to this function: the XHR instance, a status message string (in this case, always error), and an optional exception object returned from the XHR instance. complete Function A function called upon completion of the request. Two arguments are passed: the XHR instance and a status message string of either success or error. If either a success or error callback is also specified, this function is invoked after the callback is called.
    • Options for the $.ajax() utility function Name Type Utility beforeSend Function A function invoked prior to initiating the request. This function is passed the XHR instance and can be used to set custom headers or to perform other pre-request operations. async Boolean If specified as false, the request is submitted as a synchronous request, By default, the request is asynchronous processData Boolean If set to false, prevents the data passed from being processed into URL-encoded format. By default, the data is URL-encoded into a format suitable for use with requests of type application/x-www-form-urlencoded. ifModified Boolean If true, allows a request to succeed only if the response content has not changed since the last request according to the Last-Modified header. If omitted, no header check is performed.
    • Setting request defaults Command syntax : $.ajaxSetup $.ajaxSetup(properties)
        Establishes the passed set of properties as the defaults for subsequent calls to $.ajax().
      Parameters properties (Object) An object instance whose properties define the set of default Ajax properties. These are the same properties described for the $.ajax() Returns Undefined
    • $.ajaxSetup examples
      • On the beginning of <script> :
      $.ajaxSetup({ type: 'POST', timeout: 5000, dataType: 'html', error: function(xhr) { $('#errorDisplay) .html('Error: ' + xhr.status + ' ' + xhr.statusText); } }) This would ensure that every subsequent Ajax call (again, except via load()) would use these defaults, unless explicitly overridden in the properties passed to the Ajax utility function being used. Now, what about those global functions that were controlled by the global property?
    • Global Functions Command syntax: Ajax global functions ajaxStart(callback) ajaxSend(callback) ajaxSuccess(callback) ajaxError(callback) ajaxComplete(callback) ajaxStop(callback) Attaches the passed function to all matched elements invoked when the specified point in the processing of an Ajax request takes place. Parameters callback (Function) The callback function to be attached. See next slied for information on when the callback is invoked and what parameters it will be passed. Returns The wrapped set.
    • Global Ajax callbacks, listen in order of firing Global callback type When invoked Parameters ajaxStart
        When a jQuery Ajax function or command is started, but before the XHR instance is created
      A Global Callback Info object with type set to ajaxStart ajaxSend After the XHR instance has been created, but before it's sent to the server
      • A Global Callback Info object with type set to ajaxSend
      • The XHR instance
      • The properties used by the $.ajax() function
      ajaxSuccess After the request has returned from the server and the response contains a success status code
      • A Global Callback Info object with type set to ajaxSend
      • The XHR instance
      • The properties used by the $.ajax() function
    • Global Ajax callbacks, listen in order of firing Global callback type When invoked Parameters
        ajaxError
      After the request has returned from the server and the response contains a failure status code
      • A Global Callback Info Object with type set to ajaxError
      • The XHR instance
      • The properties used by the $.ajax() function
      • An exception object returned by the XHR instance, if any
      ajaxComplete After the request has returned from the server and after any declared ajaxSuccess or ajaxError have been invoked
      • A Global Callback Info object with type set to ajaxComplete
      • The XHR instance
      • The properties used by the $.ajax() function
      ajaxStop After all other Ajax processing is complete and any other applicable global callbacks have been invoked
      • A Global Callback Info object with type set to ajaxStop
    • Global Function in Action
    • The HTML <body> <fieldset> <legend>Initiate Ajax Requests</legend> <div> <button type=&quot;button&quot; id=&quot;goodButton&quot;> Initiate successful request </button> <button type=&quot;button&quot; id=&quot;badButton&quot;> Initiate failed request </button> </div> </fieldset> <fieldset> <legend>Success display</legend> <div id=&quot;successDisplay&quot;></div> </fieldset> <fieldset> <legend>Error display</legend> <div id=&quot;errorDisplay&quot;></div> </fieldset> </body>
    • The Handlers
      • The ready handler for the page has three tasks:
        • Set up the click handlers for the buttons
        • Establish a global function as a success listener attached to the success area
        • Establish a global function as a failure listener attached to the error area
    • The Handlers $('#goodButton').click(function(){ $.get('reflectData.jsp'); }); $('#badButton').click(function(){ $.get('returnError.jsp'); }); $('#successDisplay').ajaxSuccess(function(info){ $(info.target) .append('<div>Success at '+new Date()+'</div>'); }); $('#errorDisplay').ajaxError(function(info,xhr){ $(info.target) .append('<div>Failed at '+new Date()+'</div>') .append('<div>Status: ' + xhr.status + ' ' + xhr.statusText+'</div>'); });
    •  
    • Putting it all together
    • (function($) { $.fn.termifier = function(options) { options = $.extend({ lookupResource: 'getTerm', flyoutClass: 'lookerUpperFlyout' },options||{}); this.attr('title','Click me for my definition!'); return this.click(function(event){ $.ajax({ url: options.lookupResource, type: 'get', data: {term: this.innerHTML}, dataType: 'html', success: function(data) { $('<div></div>') .css({ position: 'absolute', left: event.pageX, top: event.pageY, cursor: 'pointer', display: 'none' }) .html(data) .addClass(options.flyoutClass) .click(function(){ $(this).fadeOut(1500,function(){$(this).remove();}); }) .appendTo('body') .fadeIn(); } }); return false; }); } })(jQuery); Implementation of termifier() Not Finished Yet ...
    • Q&A
    • Reference
      • Jquery in Action, Bear Bibeault, Yehuda Katz , Manning