Thursday, January 11, 2018

Ajax Quick Tutorial


AJAX stands for Asynchronous JavaScript and XML. AJAX is not a programming language but a technique for creating interactive web applications. It sends and receives data from client browser to server(independent of server technology).

Significance

  • Though XML is the common format, Ajax supports other types like plain text, Json
  • It allows web pages to be updated asynchronously by exchanging data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.


Limitations

  • AJAX has browser incompatibility 
  • For security reasons, modern browsers do not allow access across domains data


Workflow

  • Trigger (on page load, onclick, onchange, etc,.)
  • create XMLHttpRequest object in JavaScript
  • send a request to a web server
  • receive the response
  • process the response in JavaScript


3 Way to use Ajax

Direct Method

function loadDoc() {
  var xhttp = new XMLHttpRequest(); //create XMLHttpRequest object in JavaScript
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) //checking the status and read the data
{document.getElementById("result").innerHTML = this.responseText;}
  };
  xhttp.open("GET", "feed.xml", true); // get or post
  xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");//to set header for content type or cookies
  xhttp.send("m=1&type=summary");//for get parameters can be passed
  xhttp.send();
}

-----------
Callback Method
onclick="loadDoc('ajax_info.txt', myFunction)"

function loadDoc(url, cFunction) {
  var xhttp;
  xhttp=new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {cFunction(this);}
  };
  xhttp.open("GET", url, true);
  xhttp.send();
}
function myFunction(xhttp) {
  document.getElementById("result").innerHTML = xhttp.responseText;
}

JQuery Method
add Jquery lib http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js
<button id="readFile">Read File</button>
$(document).ready(function() {
    $("#readFile").click(function() {
        $.ajax({
            url : "http://macrolayer.blogspot.com/2016/03/waterways.html?m=1",
            dataType: "text",
            success : function (data) {
                alert(data.length);
                alert(data);
            }
        });
    });
});



MethodDescription
new XMLHttpRequest()Creates a new XMLHttpRequest object
abort()Cancels the current request
getAllResponseHeaders()Returns header information
getResponseHeader()Returns specific header information
open(method,url,async,user,psw)"Specifies the request
method: the request type GET or POST
url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password"
send(optional string)Sends the request to the server. parameter is used for POST requests.
setRequestHeader()set the header content to be sent


PropertyDescription
onreadystatechangeDefines a function to be called when the readyState property changes
readyState"Holds the status of the XMLHttpRequest.
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready"
responseTextReturns the response data as a string
responseXMLReturns the response data as XML data
status"Returns the status-number of a request 200: ""OK""
403: ""Forbidden""
404: ""Not Found"""
statusTextReturns the status-text (e.g. "OK" or "Not Found")