AJAX Sending a Request to a Server
Let AJAX change this text.
Change Content
Sending an XMLHttpRequest
to a Server
The
XMLHttpRequest
object is used to exchange data with 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( );
Method
Description
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.
<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", "AJAX_info.txt", true );
xmlhttp.send( );
}
</script>