jQuery Ajax

2,761 views

Published on

Introduction, Technologies included in ajax,
Ajax Evolution,
Pro’s and Con’s,
Beginners Problem?,
Types and choices of request,
Ajax on hands (Example),
Global Ajax Event Handlers,
Helper Functions,
Low Level interface,
Shorthand Methods for Ajax request.

Published in: Technology
0 Comments
2 Likes
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
2,761
On SlideShare
0
From Embeds
0
Number of Embeds
12
Actions
Shares
0
Downloads
2
Comments
0
Likes
2
Embeds 0
No embeds

No notes for slide

jQuery Ajax

  1. 1. AJAX Building faster dynamic websites - Asynchronous JavaScript and XML
  2. 2. Ajax Ajax is a group of web development methods used on the client-side to create interactive web applications. With Ajax, web applications can send data to , and retrieve data from , a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data are usually retrieved using the XMLHttpRequest object.
  3. 3. <ul><li>The term Ajax has come to represent a broad group of web technologies </li></ul><ul><li>HTML or XHTML and CSS for presentation </li></ul><ul><li>The Document Object Model (DOM) for dynamic display of and interaction with data. </li></ul><ul><li>XML for the interchange of data, and XSLT for its manipulation( JSON ) </li></ul><ul><li>The XMLHttpRequest object for asynchronous communication </li></ul><ul><li>JavaScript to bring these technologies together </li></ul>
  4. 4. Advantages <ul><li>The biggest advantages that Ajax has in web pages is that it can access information on the server without having to reload the web page . This means that to retrieve or update one small piece of information only that information needs to be passed to and from the server instead of having to redownload the entire web page. </li></ul><ul><li>Enhance your visitors experience with the web page. </li></ul><ul><li>Avoid having the Ajax interfere with the operation of the page. </li></ul><ul><li>Compatibility with JavaScript and jquery. </li></ul><ul><li>XML is replaced with JSON (alternative format for data interchange). </li></ul>
  5. 5. Disadvantages <ul><li>Pages dynamically created using successive Ajax requests do not automatically register themselves with the browser's history engine . (iframes) </li></ul><ul><li>Dynamic web page updates also make it difficult to bookmark a particular state of the application . </li></ul><ul><li>Depending on the nature of the Ajax application, dynamic page updates may interfere disruptively with user interactions , especially if working on an unstable internet connection. </li></ul><ul><li>Because most web crawlers do not execute JavaScript code, publicly indexable web applications should provide an alternative means of accessing the content that would normally be retrieved with Ajax thereby allowing search engines to index it. </li></ul>
  6. 6. Disadvantages <ul><li>Any user whose browser does not support JavaScript or XMLHttpRequest , or simply has this functionality disabled, will not be able to properly use pages which depend on Ajax. Ex: mobile phones, PDAs and screen readers. </li></ul><ul><li>The policy rules prevents some Ajax techniques from being used across domains , although the W3C has a draft of the XMLHttpRequest object that would enable this functionality. Methods exist to sidestep this security feature by using a special Cross Domain Communications channel embedded as an iframes within a page or by using JSONP. </li></ul><ul><li>Ajax-powered interfaces may dramatically increase the number of user-generated requests to web servers and their back-ends, lead to longer response times and additional hardware needs . </li></ul><ul><li>Callback-style of programming required can lead to complex code that is hard to maintain or debug. </li></ul>
  7. 7. <ul><li>There are two ways that Ajax can access the server : </li></ul><ul><li>Synchronous </li></ul><ul><li>Asynchronous </li></ul>
  8. 8. Synchronous <ul><li>Script stops and waits for the server to send back a reply before continuing. </li></ul><ul><li>Like reloading the page but with only the requested information having to be downloaded instead of the entire page. </li></ul><ul><li>Faster than not using Ajax. </li></ul><ul><li>Visitors are used to having to wait for entire web pages to download, they are not used to having to wait while interacting with a web page for any significant time and so unless the information you are requesting is particularly small so that it can be downloaded extremely quickly you run the risk of alienating visitors who may have been quite happy with a longer wait to download the entire page. </li></ul>
  9. 9. Asynchronous(99%) <ul><li>Script allows the page to continue to be processed and will handle the reply if and when it arrives. </li></ul><ul><li>Avoids the delay while the retrieval from the server is taking place because your visitor can continue to interact with the web page and the requested information will be processed with the response updating the page as and when it arrives . </li></ul><ul><li>For larger requests where the response will have a noticeable delay that delay possibly will not be noticed by your visitors because they are occupied interacting with fields further down the page. </li></ul><ul><li>Responses that are nearly instantaneous your visitors will not even be aware that a request to the server was made. </li></ul><ul><li>Most preferred way to use Ajax therefore is to use asynchronous calls </li></ul>
  10. 10. Beginners fall into trap. Why? Rare situations where it just doesn't make any sense at all to allow your visitor to continue interacting with the web page until a particular server side process completes. The only difference when using asynchronous calls is that you can actually set up multiple Ajax calls that overlap with a second call being made before the first has responded. This is where asynchronous Ajax does become slightly more complicated than synchronous Ajax because you need to make sure that each Ajax request uses a separate Ajax object rather than reusing the same object for all your Ajax requests
  11. 11. Two choices of passing the request <ul><li>GET </li></ul><ul><li>POST </li></ul><ul><li>GET Call data limit = Data that can be passed when requesting a new page load. </li></ul><ul><li> The best solution when you have lots of data to pass like that is to make multiple Ajax calls passing a few pieces of information at a time. </li></ul>
  12. 12. Passing request to server: Differences <ul><li>First difference is that you are only requesting a small piece of information instead of an entire web page. </li></ul><ul><li>The second and most noticeable difference is that since the Ajax request doesn't appear in the address bar there is no noticeable difference that your visitor will see on their screen when the request is made. </li></ul><ul><li>Calls made using GET will not expose the fields and their values anywhere neither do POST, when the call is made from Ajax. – Secured. </li></ul>
  13. 13. How to choose between GET & POST? <ul><li>Purpose of GET - to GET information , intended to be used when you are reading information to display on the page. </li></ul><ul><li>Browsers will automatically cache the result from a GET request and if the same GET request is made again then they will display the cached result rather than rerunning the entire request. </li></ul><ul><li>A GET call is retrieving data to display in the page and data is not expected to be changed on the server by such a call and so re-requesting the same data should be expected to obtain the same result. </li></ul>
  14. 14. How to choose between GET & POST? <ul><li>POST method is intended to be used where you are updating information on the server . </li></ul><ul><li>Results returned from server . </li></ul><ul><li>A POST call will therefore always obtain the response from the server rather than keeping a cached copy of the prior response. </li></ul><ul><li>If the value to be retrieved is expected to vary over time as a result of other processes updating it then add a current time parameter to what you are passing in your GET call. </li></ul><ul><li>These criteria is not only for GET and POST for your Ajax calls but also to GET or POST when processing forms on your web page as well. </li></ul>
  15. 15. Ajax jQuery syntax jQuery.ajax( url, [settings] ) Or jQuery.ajax( settings ) Url : A string containing the URL to which the request is sent . Settings : A set of key/value pairs that configure the Ajax request . All settings are optional . A default can be set for any option with $.ajaxSetup() .
  16. 16. Settings Accepts ( Map -depends on Datatype): The content type sent in the request header that tells the server what kind of response it will accept in return. Async(Boolean-true): By default, all requests are sent asynchronously . If you need synchronous requests, set this option to false. Synchronous requests may temporarily lock the browser . BeforeSend(jqXHR, settings)- Function A pre-request callback function that can be used to modify the jqXHR object before it is sent. Used to set custom headers, etc.
  17. 17. Settings Cache(Boolean-true, false for DataType 'script' and 'jsonp'): If set to false, it will force requested pages not to be cached by the browser . Setting cache to false also appends a query string parameter, &quot;_=[TIMESTAMP]&quot; , to the URL. Complete(jqXHR, textStatus)-Function,Array A function to be called when the request finishes . Two arguments: The jqXHR object and a string categorizing the status of the request (&quot;success&quot;, &quot;notmodified&quot;, &quot;error&quot;, &quot;timeout&quot;, &quot;abort&quot;, or &quot;parsererror&quot;). Contents(1.5) A map of string/regular-expression pairs that determine how jQuery will parse the response , given its content type.
  18. 18. Settings ContentType(String-'application/x-www-form-urlencoded‘) When sending data to the server, uses this content-type . Context(Object) This object will be made the context of all Ajax-related callbacks. Converters(Map) A map of dataType-to-dataType converters . Each converter's value is a function that returns the transformed value of the response.
  19. 19. Settings CrossDomain(Boolean-false for same-domain requests, true for cross-domain requests) Set the value of crossDomain to true for, server-side redirection to another domain . Data(Object) Data to be sent to the server . It is converted to a query string , if not already a string. It's appended to the url for GET-requests. Key-value pairs . DataType(String-Intelligent Guess-xml, json, script, or html) The type of data that you're expecting back from the server .
  20. 20. Settings Error(jqXHR, textStatus, errorThrown)- Function A function to be called if the request fails . TextStatus-&quot;timeout&quot;, &quot;error&quot;, &quot;abort&quot;, and &quot;parsererror“ and ErrorThrown- for HTTP errors. &quot;Not Found&quot; or &quot;Internal Server Error.“ Global(Boolean-true) Whether to trigger global Ajax event handlers for this request. Set to false to prevent the global handlers like ajaxStart or ajaxStop from being triggered. Headers(1.5) A map of additional header key/value pairs to send along with the request. This setting is set before the beforeSend function is called; therefore, any values in the headers setting can be overwritten from within the beforeSend function.
  21. 21. Settings IfModified(Boolean-false) Allow the request to be successful only if the response has changed since the last request. IsLocal(1.5) Allow the current environment to be recognized as &quot;local&quot; (e.g. the filesystem) Jsonp(String) Override the callback function name in a jsonp request.
  22. 22. Settings JsonpCallback(String) Specify the callback function name for a JSONP request. MimeType(1.5) A mime type to override the XHR mime type. Password(String) and Username(String A password to be used in response to an HTTP access authentication request. ProcessData(Boolean-true) By default data is processed as QueryString. Any DOMDocument or non-processed data set it to false.
  23. 23. Settings ScriptCharset(String) Only for requests with &quot;jsonp&quot; or &quot;script&quot; dataType and &quot;GET&quot; type. Forces the request to be interpreted as a certain charset . StatusCode(1.5) A map of numeric HTTP codes and functions to be called when the response has the corresponding code. Success(data, textStatus, jqXHR) A function to be called if the request succeeds . Timeout(Number) Set a local timeout (in milliseconds) for the request.
  24. 24. Settings Type(String-GET) The type of request to make (&quot;POST&quot; or &quot;GET&quot;). Url(String- The current page) A string containing the URL to which the request is sent . Xhr(Function-ActiveXObject) Callback for creating the XMLHttpRequest object. XhrFields(Map) A map of fieldName-fieldValue pairs to set on the native XHR object . Ex: Set withCredentials to true for cross-domain requests if needed
  25. 25. The jqXHR Object <ul><li>jQuery XMLHttpRequest (jqXHR) object returned by $.ajax() is a superset of the browser's native XMLHttpRequest object. For example, it contains responseText and responseXML properties, as well as a getResponseHeader() method. </li></ul><ul><li>.error() </li></ul><ul><li>.success() </li></ul><ul><li>.complete() </li></ul><ul><li>jqXHR.done(), jqXHR.fail(), and jqXHR.always() in jQuery 1.8. </li></ul>
  26. 26. AJAX on Hands
  27. 27. Global Ajax Event Handlers <ul><li>.ajaxComplete() </li></ul><ul><li>Register a handler to be called when Ajax requests complete . </li></ul><ul><li>.ajaxError() </li></ul><ul><li>Register a handler to be called when Ajax requests complete with an error . </li></ul><ul><li>.ajaxSend() </li></ul><ul><li>Attach a function to be executed before an Ajax request is sent . </li></ul>
  28. 28. Global Ajax Event Handlers <ul><li>.ajaxStart() </li></ul><ul><li>Register a handler to be called when the first Ajax request begins . </li></ul><ul><li>.ajaxStop() </li></ul><ul><li>Register a handler to be called when all Ajax requests have completed . </li></ul><ul><li>.ajaxSuccess() </li></ul><ul><li>Attach a function to be executed whenever an Ajax request completes successfully . </li></ul>
  29. 29. Helper Functions <ul><li>jQuery.param() </li></ul><ul><li>Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. </li></ul><ul><li>.serialize() </li></ul><ul><li>Forms Encode a set of form elements as a string for submission . </li></ul><ul><li>.serializeArray() </li></ul><ul><li>Forms Encode a set of form elements as an array of names and values. </li></ul>
  30. 30. Low-Level Interface <ul><li>These methods can be used to make arbitrary AJAX requests. </li></ul><ul><li>jQuery.ajax() </li></ul><ul><li>Perform an asynchronous HTTP (Ajax) request . </li></ul><ul><li>jQuery.ajaxPrefilter() </li></ul><ul><li>Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). </li></ul><ul><li>jQuery.ajaxSetup() </li></ul><ul><li>Set default values for future Ajax requests . </li></ul>
  31. 31. Shorthand Methods <ul><li>These methods perform the more common types of AJAX requests in less code. </li></ul><ul><li>jQuery.get() </li></ul><ul><li>Load data from the server using a HTTP GET request . </li></ul><ul><li>jQuery.getJSON() </li></ul><ul><li>Load JSON-encoded data from the server using a GET HTTP request. </li></ul><ul><li>jQuery.getScript() </li></ul><ul><li>Load a JavaScript file from the server using a GET HTTP request , then execute it. </li></ul>
  32. 32. Shorthand Methods <ul><li>.load() </li></ul><ul><li>Load data from the server and place the returned HTML into the matched element. </li></ul><ul><li>jQuery.post() </li></ul><ul><li>Load data from the server using a HTTP POST request . </li></ul>
  33. 33. No Queries? THANK YOU

×