The document discusses using Ajax with jQuery to make requests to a server. It provides an overview of Ajax, describes how to make GET and POST requests with jQuery's $.get() and $.getJSON() methods, and gives an example of loading dependent dropdowns by making cascading Ajax calls based on user selection. Key points covered include initializing XHR objects, handling responses, and loading/filtering HTML snippets or JSON data into the DOM.
10. 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"); }
11. 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
16. 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
19. Let the XHR instance know how it can inform us of its progress
20. 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
36. 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 ...
37. 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
39. The HTML Markup <body id="bootCloset1"> <img id="banner" src="boot.closet.branding.png"/> <form action="" id="orderForm"> <div id="detailFormContainer"> <h1>Choose your boots</h1> <div> <label>Please choose a style:</label><br/> <select id="styleDropdown"> <option value="">Please choose a boot style</option> <option value="7177382">Caterpillar Tradesman Work Boot</option> <option value="7269643">Caterpillar Logger Boot</option> <option value="7141832">Chippewa 17" Engineer Boot</option> <option value="7141833">Chippewa 17" Snakeproof Boot</option> <option value="7173656">Chippewa 11" Engineer Boot</option> <option value="7141922">Chippewa Harness Boot</option> <option value="7141730">Danner Foreman Pro Work Boot</option> <option value="7257914">Danner Grouse GTX Boot</option> </select> </div> <div id="detailsDisplay"></div> </div> </form> </body> s Empty <div>
40. 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
41. The server-side resource returns a pre-formatted fragment of HTML to display the boot information.
42.
43. 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.
49. 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
50. 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("disabled",true); $(dropdownSet).emptySelect(); adjustSizeDropdown(); } else { dropdownSet.attr("disabled",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
51. adjustSizeDropdown() function adjustSizeDropdown() { var styleValue = $('#styleDropdown').val(); var colorValue = $('#colorDropdown').val(); var dropdownSet = $('#sizeDropdown'); if ((styleValue.length == 0)||(colorValue.length == 0) ) { dropdownSet.attr("disabled",true); $(dropdownSet).emptySelect(); }else { dropdownSet.attr("disabled",false); $.getJSON( 'getSizes.jsp', {style:styleValue,color:colorValue}, function(data){$(dropdownSet).loadSelect(data)} ); } }
53. 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); } }); } }); }
54. 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);
55. 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!
56.
57.
58.
59. 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.
60. 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.
61.
62. json—The response text is evaluated as a JSON string, and the resulting object is passed to the callbacks.
63. jsonp—Similar to json except that remote scripting is allowed,assuming the remote server supports it.
64.
65.
66.
67. 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.
68.
69.
70. 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.