XML DOM tutoria...LOGIN
XML DOM tutorial
author:php.cn  update time:2022-04-13 15:27:56

DOM XMLHttpRequest


The XMLHttpRequest Object


The XMLHttpRequest object allows you to update a portion of a web page without reloading the entire page.


XMLHttpRequest Object

The XMLHttpRequest object is used behind the scenes to exchange data with the server.

The XMLHttpRequest object is a developer's dream because you can:

  • Update web pages without reloading the page

  • Request data from the server after the page has loaded

  • Receive data from the server after the page has loaded

  • Send data to the server in the background


Create XMLHttpRequest object

All modern browsers (IE7+, Firefox, Chrome, Safari and Opera) have an in- Create an XMLHttpRequest object.

Syntax for creating XMLHttpRequest objects

xmlhttp=new XMLHttpRequest();

Older versions of Internet Explorer (IE5 and IE6) use ActiveX objects:

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

To handle all modern browsers, including IE5 and IE6, please check if the browser supports XMLHttpRequest object. If supported, create an XMLHttpRequest object, if not supported, create an ActiveX object:

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

Running Instance»

Click the "Run Instance" button to view the online instance



Send a request to the server

In order to send a request to the server, we use the XMLHttpRequest object The open() and send() methods:

xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();

MethodDescription
open(method,url,async) Specifies the type of request, URL, and whether the request should be processed asynchronously.

method: Type of request: GET or POST
url: The location of the file on the server
async: true (asynchronous) or false (synchronous)
send(string)Send the request to the server.

string: For POST requests only


GET or POST?

GET is simpler and faster than POST and can be used in most situations.

However, always use POST requests in the following cases:

  • Cached files are not an option (updating files or databases on the server)

  • The amount of data sent to the server is large (POST has no size limit)

  • Send user input (can contain unknown characters), POST is more powerful and more powerful than GET Security


URL - File on the server

The url parameter of the open() method is the address of a file on the server:

xmlhttp.open("GET","xmlhttp_info.txt",true);

The file can be any type of file (such as .txt and .xml), or a server Script files (such as .html and .php that perform actions on the server before sending a response back).


Asynchronous - True or False?

If you need to send a request asynchronously, the async parameter of the open() method must be set to true:

xmlhttp. open("GET","xmlhttp_info.txt",true);

Sending asynchronous requests is a huge improvement for web developers. Many tasks performed on the server are very time-consuming.

By sending asynchronously, JavaScript does not need to wait for the server's response, but can be replaced with:

  • While waiting for the server's response, execute other scripts

  • Processing the response when the response is ready


Async=true

When using async=true, it is specified in the onreadystatechange event when the response is ready A function to be executed:

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

Run Instance»

Click the "Run Instance" button to view the online instance



Async=false

If you need to use async=false, please change the third parameter of the open() method to false:

xmlhttp.open("GET","xmlhttp_info.txt",false);

It is not recommended to use async=false, but it is still possible if you handle a few small requests.

Remember that JavaScript will not continue execution until the server response is ready. If the server is busy or slow, the application will hang or stop.

Note: Do not write onreadystatechange when you use async=false Functions - Just place the code after the send() statement:

Example

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmlhttp.open("GET","xmlhttp_info.txt",false);
  xmlhttp.send();
  document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

Run Example»

Click the "Run Instance" button to view the online instance



Server response

To get a response from the server, use the responseText or responseXML property of the XMLHttpRequest object.

PropertiesDescription
responseTextGet the response data as a string
responseXMLGet response data as XML data


##responseText attribute

If the response from the server is not XML, use the responseText attribute.

responseText property returns the response as a string, you can use it accordingly:

Example

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

Running Example »Click the "Run Instance" button to view the online instance



responseXML attribute

If the response from the server is not XML and you want To parse it into an XML object, use the responseXML attribute:

Example

Request the file cd_catalog.xml and parse the response:

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
xmlhttp=null;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
if (xmlhttp!=null)
  {
  xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
      {
      xmlDoc=xmlhttp.responseXML;
      var txt="";
      x=xmlDoc.getElementsByTagName("ARTIST");
      for (i=0;i<x.length;i++)
        {
        txt=txt + x[i].childNodes[0].nodeValue + "<br>";
        }
      document.getElementById("myDiv").innerHTML=txt;
        }
      }
  xmlhttp.open("GET","cd_catalog.xml",true);
  xmlhttp.send();
  }
else
  {
  alert("Your browser does not support XMLHTTP.");
  }
}
</script>
</head>
<body>

<h2>My CD Collection:</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Get my CD collection</button>

</body>
</html>

Run Instance»Click the "Run Instance" button to view the online instance



onreadystatechange event

When the request is sent to Server, we want to perform some action based on the response.

onreadystatechange event is triggered every time readyState changes.

The readyState attribute holds the status of XMLHttpRequest.

Three important attributes of the XMLHttpRequest object:

AttributeDescription onreadystatechangeThe storage function (or the name of the function) is automatically called every time the readyState attribute changesreadyStateStores the state of XMLHttpRequest. Change from 0 to 4: status200: "OK"

In the onreadystatechange event, we specify what happens when the server's response is ready to be processed.

When readyState is 4 or status is 200, response preparation:

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","xmlhttp_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>Using the XMLHttpRequest object</h2>
<div id="myDiv"></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body>
</html>

Run instance»

Click the "Run Instance" button to view the online instance

Note: The onreadystatechange event is triggered every time readyState changes, a total of four times.


tryitimg.gifMore examples


Retrieve header information through getAllResponseHeaders()
Retrieve resources (files ) header information.

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('p1').innerHTML=xmlhttp.getAllResponseHeaders();
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<p id="p1">The getAllResponseHeaders() function returns the header information of a resource, like length, server-type, content-type, last-modified, etc.</p>
<button onclick="loadXMLDoc('xmlhttp_info.txt')">Get header information</button>

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance


Retrieve the specified header information through getResponseHeader()
Retrieve the specified header information of the resource (file).

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById('p1').innerHTML="Last modified: " + xmlhttp.getResponseHeader('Last-Modified');
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<p id="p1">The getResponseHeader() function is used to return specific header information from a resource, like length, server-type, content-type, last-modified, etc.</p>
<button onclick="loadXMLDoc('xmlhttp_info.txt')">Get "Last-Modified" information</button>

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance


Retrieve the contents of an ASP file
How a web page communicates with the web server when the user types characters in the input field.

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function showHint(str)
{
if (str.length==0)
  { 
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","gethint.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<h3>Start typing a name in the input field below:</h3>
<form action=""> 
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)" />
</form>
<p>Suggestions: <span id="txtHint"></span></p> 

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance


Retrieve content from the database
How web pages extract information from the database through the XMLHttpRequest object.

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function showCustomer(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }  
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getcustomer.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form action=""> 
<select name="customers" onchange="showCustomer(this.value)">
<option value="">Select a customer:</option>
<option value="ALFKI">Alfreds Futterkiste</option>
<option value="NORTS ">North/South</option>
<option value="WOLZA">Wolski Zajazd</option>
</select>
</form>
<br>
<div id="txtHint">Customer info will be listed here...</div>

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance


Retrieve the contents of an XML file
Create an XMLHttpRequest to retrieve data from an XML file and display the data in an HTML table.

Instance

<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc(url)
{
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    txt="<table border='1'><tr><th>Title</th><th>Artist</th></tr>";
    x=xmlhttp.responseXML.documentElement.getElementsByTagName("CD");
    for (i=0;i<x.length;i++)
      {
      txt=txt + "<tr>";
      xx=x[i].getElementsByTagName("TITLE");
        {
        try
          {
          txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
          }
        catch (er)
          {
          txt=txt + "<td> </td>";
          }
        }
      xx=x[i].getElementsByTagName("ARTIST");
        {
        try
          {
          txt=txt + "<td>" + xx[0].firstChild.nodeValue + "</td>";
          }
        catch (er)
          {
          txt=txt + "<td> </td>";
          }
        }
      txt=txt + "</tr>";
      }
    txt=txt + "</table>";
    document.getElementById('txtCDInfo').innerHTML=txt;
    }
  }
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
</script>
</head>
<body>

<div id="txtCDInfo">
<button onclick="loadXMLDoc('cd_catalog.xml')">Get CD info</button>
</div>

</body>
</html>

Run instance»

Click the "Run instance" button to view the online instance


0: The request is not initialized
1: Server establishes connection
2: Request received
3: Process the request
4: Request completed and response ready
404: Page not found