Skip to main content

XML : AJAX Tutorial For Beginners

Why Study AJAX?
If you want to learn :
• Update a web page without reloading the page
• Request data from a server - after the page has loaded
• Receive data from a server - after the page has loaded
• Send data to a server - in the background
What is AJAX?
AJAX stands for Asynchronous JavaScript And XML.
AJAX is not a programming Language.
Ajax just uses a combination of :
A browser built-in XMLHttpRequest object (to request data from a web server)
JavaScript and HTML DOM (to display or use the data)
This is how AJAX works:-

<!DOCTYPE html>
<html>
<head>
<script>
function tryAjax() {
  var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      document.getElementById("content").innerHTML = this.responseText;
    }
  };
  xhttp.open("GET", "file.txt", true);
  xhttp.send();
}
</script>
</head>
<body>

<div id="content">
 <h1>The XMLHttpRequest Object</h1>
 <button type="button" onclick="tryAjax()">Change Content</button>
</div>
</body>
</html>
Code Explanation:
When Button is Clicked, enent occurs and tryAjax() is called.
XMLHttpRequest object is created by Script
XMLHttpRequest object sends a request to a web server
through xhttp.open("method",URL,async)
URL is an address to a file on a server:
the file can be any kind of file, like .txt and .xml or server Scripting files like .asp and .php(which can perform certain actions on the server before sending the response back.
Server requests should be sent Asynchronously.
so that JavaScript does not have to wait for the server response.
The server processes the request
The server sends a response back to the web page
The response is read by JavaScript
onreadystatechange Property
With XMLHttpRequest object you can define a function to be executed when the request receives an answer.
The function is defined in the property of XMLHttpRequest called onreadystatechange
Proper action (like page update) is performed by JavaScript
AJAX - XMLHttpRequest Object
The XMLHttpRequest object is the key to AJAX as it can be used to exchange data with a server behind the scenes because of an independent connection channel.
XMLHttpRequest Object Methods
Method Description
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)
open(method, url, async, user)
open(method, url, async)
open(method, url)
specifies the request:
method:(get, post)
url:(location of file)
async:optional(true,false),default:true
user:optional(user name)
psw:optional(password)
send() Sends the request to the server Used for GET requests
send(string) Sends the request to the server. Used for POST requests.
setRequestHeader() Adds a label/value pair to the header to be sent
XMLHttpRequest Object Properties
Property Description
onreadystatechange Defines a function to be called when the readyState property changes
ReadyState Holds the status of the XMLHttpRequest
0:The request is not initialized
1:the request has been set up
2:the request has been sent
3:the request is in process
4:the request is completed.
responseText Returns the response data as a string
responseXML Returns the response data as XML data
status Returns the status as a number 200:OK 403:Forbidden 404:Not Found
statusText Returns the status-text :OK OR : Not Found
What to choose ? GET : POST
Use GET Request method if :
A cached file is an option.
Want to send small amount of data to the server
Use POST request method if :
You want to send large amount of data to the server as POSt method has no size limitaions.
You want to send user input data which may contain unknown characters, because it is more robust and secure than GET.
getAll ResponseHeaders() Method
getAllResponseHeaders() Method returns all header information from the server response.
<!DOCTYPE html>
<html>
<head>
    <script>
    var xhttp = new XMLHttpRequest();
    xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("demo").innerHTML =
                this.getAllResponseHeaders();
        }
    };
    xhttp.open("GET", "ajax_info.txt", true);
    xhttp.send();
    </script>
</head>
<body>
    <h1>The XMLHttpRequest Object</h1>
    <p>The getAllResponseHeaders() function returns all the header information of a resource, like length, server-type, content-type, last-modified, etc:</p>
    <p id="demo"></p>
</body>
</html>
      
Similarly we can execute getResponseHeader() method returns specific header information from the server response.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
    document.getElementById("demo").innerHTML =
    this.getResponseHeader("Last-Modified");
  }
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();      
Information like: date, last-modified, accept-ranges, content-length can be obtained by this method.

Comments

  1. If Anyone have any Question or Suggestion , feel free to comment...

    ReplyDelete

Post a Comment

Popular posts from this blog

Top 10 Tips To Crack Interview For Programmers

Interview have always been a nerve reaching experience. Everybody gets the jitters when it comes to interviews.Especially when you are a fresher and going to give an interview as developer. Relax! Don't Panic.Below are the best tips to help you land your dream job. ->Understanding the requirement Read the job descreption carefully. It is important to understand,what is expected from you and whether you fit in that given profile or not. Analysing your personal strength and weakness alongside helps in deciding how well the job suits you and how to approach the interview. ->Know the employer Study about the company where you are appearing for the interview  Know their history  their vision  their objectives so that you are able to answer the questions on it. Research well on their future plans so that you are able to align with your job role and you can benifit them in the long term. ->Prepare well in advance You must be pr...

Cpp Question : Calculating Price of Eggs

Diary Farm sells organic brown eggs to local customers. They charge Rs 22.50 for a dozen for eggs, or rs 2.10 for individual effs that are not part of a dozen. Write a C++ Program a user for the number of eggs in the order and the displays the amount owned with a full explanation. For Example, typical output might be " You ordered 27 eggs. that's 2 dozens at rs 2.50 per dozen and 3 loose eggs at rs 2.10 each for a total of rs 51.30". The program must iterate until zero is entered for the number of eggs. Code: #include<iostream> using namespace std; int main(void) { int n; float price=0; int r=0,q; char ch; do { cout<<"\nEnter Numbe of eggs OR zero (0) to exit :"; cin>>n; if(n<0) { cout<<"Incorect Value"; } else if(n==0) { exit(0); } else { q=n/12; price+=q*22.50; r=n%12; ...