Tuesday 24 January 2012

AJAX - Send a Request To a Server


To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();

MethodDescription
open(method,url,async)Specifies the type of request, the URL, and if the request should be handled asynchronously or not.

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

string: Only used for POST requests


GET or POST?

GET is simpler and faster than POST, and can be used in most cases.
However, always use POST requests when:
  • A cached file is not an option (update a file or database on the server)
  • Sending a large amount of data to the server (POST has no size limitations)
  • Sending user input (which can contain unknown characters), POST is more robust and secure than GET

GET Requests

A simple GET request:

Example

xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();




<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
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","demo_get.asp",true);
xmlhttp.send();
}
</script>
</head>
<body>

<h2>AJAX</h2>
<button type="button" onclick="loadXMLDoc()">Request data</button>
<div id="myDiv"></div>

</body>
</html>

No comments: