KEMBAR78
jQuery Ajax | PPT
AJAX Building faster dynamic websites - Asynchronous JavaScript and XML
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.
The term  Ajax  has come to represent a broad group of web technologies HTML  or  XHTML  and  CSS  for presentation The  Document Object Model  (DOM) for dynamic display of and interaction with data. XML  for the interchange of data, and  XSLT  for its manipulation( JSON ) The  XMLHttpRequest  object for asynchronous communication JavaScript  to bring these technologies together
Advantages 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. Enhance your visitors experience  with the web page. Avoid having the Ajax interfere  with the operation of the page. Compatibility  with JavaScript and jquery. XML is replaced with  JSON (alternative format for data interchange).
Disadvantages Pages dynamically created using successive Ajax requests do not  automatically register themselves  with the browser's history engine . (iframes) Dynamic web page updates also make it difficult to  bookmark a particular state of the application . 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. 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.
Disadvantages 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. 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. 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 . Callback-style of programming required  can lead to complex code  that is hard  to maintain or debug.
There are two ways that Ajax can access the server : Synchronous Asynchronous
Synchronous Script  stops and waits for the server  to send back a reply before continuing. Like reloading the page but  with only the requested information  having to be downloaded instead of the entire page. Faster  than not using Ajax. 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.
Asynchronous(99%) Script   allows the page to continue to be processed  and will handle the reply if and when it arrives. 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 . 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. Responses that are nearly instantaneous your  visitors will not even be aware  that a request to the server was made. Most preferred way  to use Ajax therefore is to use asynchronous calls
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
Two choices of passing the request GET POST GET Call data limit = Data that can be passed when requesting a new page load.   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.
Passing request to server: Differences First difference is that you are only  requesting a small piece of information  instead of an entire web page. 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. Calls made using GET  will not expose the fields  and their values anywhere  neither do POST,  when the call is made from Ajax. – Secured.
How to choose between GET & POST? Purpose of GET -  to GET information , intended to be used when you are reading information to display on the page. 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. 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.
How to choose between GET & POST? POST method is intended to be used where you are  updating information on the server . Results  returned from server . A POST call will therefore always  obtain the response from the server  rather than keeping a cached copy of the prior response. 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. 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.
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() .
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.
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, "_=[TIMESTAMP]" , 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  ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). Contents(1.5) A map of string/regular-expression pairs that  determine how jQuery will parse the response , given its content type.
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.
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 .
Settings Error(jqXHR, textStatus, errorThrown)- Function A function to be called if the  request fails . TextStatus-"timeout", "error", "abort", and "parsererror“ and ErrorThrown- for HTTP errors. "Not Found" or "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.
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 "local"  (e.g. the filesystem) Jsonp(String) Override the callback function  name in a jsonp request.
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.
Settings ScriptCharset(String)   Only for requests with  "jsonp" or "script"  dataType and  "GET"  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.
Settings Type(String-GET)   The  type of request  to make ("POST" or "GET"). 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
The jqXHR Object 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. .error() .success() .complete() jqXHR.done(), jqXHR.fail(), and jqXHR.always() in jQuery 1.8.
AJAX on Hands
Global Ajax Event Handlers .ajaxComplete() Register a handler to be called when  Ajax requests complete .  .ajaxError() Register a handler to be called when Ajax requests complete  with an error .  .ajaxSend() Attach a function to be executed before an  Ajax request is sent .
Global Ajax Event Handlers .ajaxStart() Register a handler to be called when the  first Ajax request begins . .ajaxStop() Register a handler to be called when all  Ajax requests have completed .  .ajaxSuccess() Attach a function to be executed whenever an  Ajax request completes successfully .
Helper Functions jQuery.param() Create a  serialized representation of an array  or object, suitable for use in a URL query string or Ajax request. .serialize() Forms Encode a set of  form elements as a string for submission . .serializeArray() Forms  Encode a set of form elements as an array  of names and values.
Low-Level Interface These methods can be used to make arbitrary AJAX requests. jQuery.ajax() Perform an  asynchronous HTTP (Ajax) request . jQuery.ajaxPrefilter() Handle  custom Ajax options or modify existing options  before each request is sent and before they are processed by $.ajax(). jQuery.ajaxSetup() Set  default values for future Ajax requests .
Shorthand Methods These methods perform the more common types of AJAX requests in less code. jQuery.get() Load data from the  server using a HTTP GET request . jQuery.getJSON() Load  JSON-encoded data from the server  using a GET HTTP request. jQuery.getScript() Load a  JavaScript file from the server using a GET HTTP request , then execute it.
Shorthand Methods .load() Load  data from the server and place the returned HTML  into the matched element. jQuery.post() Load data from the  server using a HTTP POST request .
No Queries? THANK YOU

jQuery Ajax

  • 1.
    AJAX Building fasterdynamic websites - Asynchronous JavaScript and XML
  • 2.
    Ajax Ajax isa 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.
    The term Ajax has come to represent a broad group of web technologies HTML or XHTML and CSS for presentation The Document Object Model (DOM) for dynamic display of and interaction with data. XML for the interchange of data, and XSLT for its manipulation( JSON ) The XMLHttpRequest object for asynchronous communication JavaScript to bring these technologies together
  • 4.
    Advantages The biggestadvantages 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. Enhance your visitors experience with the web page. Avoid having the Ajax interfere with the operation of the page. Compatibility with JavaScript and jquery. XML is replaced with JSON (alternative format for data interchange).
  • 5.
    Disadvantages Pages dynamicallycreated using successive Ajax requests do not automatically register themselves with the browser's history engine . (iframes) Dynamic web page updates also make it difficult to bookmark a particular state of the application . 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. 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.
  • 6.
    Disadvantages Any userwhose 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. 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. 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 . Callback-style of programming required can lead to complex code that is hard to maintain or debug.
  • 7.
    There are twoways that Ajax can access the server : Synchronous Asynchronous
  • 8.
    Synchronous Script stops and waits for the server to send back a reply before continuing. Like reloading the page but with only the requested information having to be downloaded instead of the entire page. Faster than not using Ajax. 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.
  • 9.
    Asynchronous(99%) Script allows the page to continue to be processed and will handle the reply if and when it arrives. 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 . 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. Responses that are nearly instantaneous your visitors will not even be aware that a request to the server was made. Most preferred way to use Ajax therefore is to use asynchronous calls
  • 10.
    Beginners fall intotrap. 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.
    Two choices ofpassing the request GET POST GET Call data limit = Data that can be passed when requesting a new page load. 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.
  • 12.
    Passing request toserver: Differences First difference is that you are only requesting a small piece of information instead of an entire web page. 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. Calls made using GET will not expose the fields and their values anywhere neither do POST, when the call is made from Ajax. – Secured.
  • 13.
    How to choosebetween GET & POST? Purpose of GET - to GET information , intended to be used when you are reading information to display on the page. 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. 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.
  • 14.
    How to choosebetween GET & POST? POST method is intended to be used where you are updating information on the server . Results returned from server . A POST call will therefore always obtain the response from the server rather than keeping a cached copy of the prior response. 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. 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.
  • 15.
    Ajax jQuery syntaxjQuery.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.
    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.
    Settings Cache(Boolean-true, falsefor 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, "_=[TIMESTAMP]" , 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 ("success", "notmodified", "error", "timeout", "abort", or "parsererror"). Contents(1.5) A map of string/regular-expression pairs that determine how jQuery will parse the response , given its content type.
  • 18.
    Settings ContentType(String-'application/x-www-form-urlencoded‘) Whensending 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.
    Settings CrossDomain(Boolean-false forsame-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.
    Settings Error(jqXHR, textStatus,errorThrown)- Function A function to be called if the request fails . TextStatus-"timeout", "error", "abort", and "parsererror“ and ErrorThrown- for HTTP errors. "Not Found" or "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.
    Settings IfModified(Boolean-false) Allowthe 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 "local" (e.g. the filesystem) Jsonp(String) Override the callback function name in a jsonp request.
  • 22.
    Settings JsonpCallback(String) Specifythe 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.
    Settings ScriptCharset(String) Only for requests with "jsonp" or "script" dataType and "GET" 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.
    Settings Type(String-GET) The type of request to make ("POST" or "GET"). 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.
    The jqXHR ObjectjQuery 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. .error() .success() .complete() jqXHR.done(), jqXHR.fail(), and jqXHR.always() in jQuery 1.8.
  • 26.
  • 27.
    Global Ajax EventHandlers .ajaxComplete() Register a handler to be called when Ajax requests complete . .ajaxError() Register a handler to be called when Ajax requests complete with an error . .ajaxSend() Attach a function to be executed before an Ajax request is sent .
  • 28.
    Global Ajax EventHandlers .ajaxStart() Register a handler to be called when the first Ajax request begins . .ajaxStop() Register a handler to be called when all Ajax requests have completed . .ajaxSuccess() Attach a function to be executed whenever an Ajax request completes successfully .
  • 29.
    Helper Functions jQuery.param()Create a serialized representation of an array or object, suitable for use in a URL query string or Ajax request. .serialize() Forms Encode a set of form elements as a string for submission . .serializeArray() Forms Encode a set of form elements as an array of names and values.
  • 30.
    Low-Level Interface Thesemethods can be used to make arbitrary AJAX requests. jQuery.ajax() Perform an asynchronous HTTP (Ajax) request . jQuery.ajaxPrefilter() Handle custom Ajax options or modify existing options before each request is sent and before they are processed by $.ajax(). jQuery.ajaxSetup() Set default values for future Ajax requests .
  • 31.
    Shorthand Methods Thesemethods perform the more common types of AJAX requests in less code. jQuery.get() Load data from the server using a HTTP GET request . jQuery.getJSON() Load JSON-encoded data from the server using a GET HTTP request. jQuery.getScript() Load a JavaScript file from the server using a GET HTTP request , then execute it.
  • 32.
    Shorthand Methods .load()Load data from the server and place the returned HTML into the matched element. jQuery.post() Load data from the server using a HTTP POST request .
  • 33.