AJAX
AJAXRead data from a web server - after the page has loadedUpdate a web page without reloading the pageSend data to a web server - in the background
XMLHttpRequest Object
All modern browsers (Chrome, Firefox, IE7+, Edge, Safari, Opera) have a built-in XMLHttpRequest
object.
Syntax for creating an XMLHttpRequest
var xhttp = new XMLHttpRequest();
request
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)
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()
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: request not initialized 1: server connection established 2: request received 3: processing request 4: request finished and response is ready
responseText
Returns the response data as a string
responseXML
Returns the response data as XML data
status
statusText
Returns the status-text (e.g. "OK" or "Not Found")
Send a Request To a Server
To send a request to a server, we use the open() and send() methods of the XMLHttpRequest
object:xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
Method
Description
open(method, url, async)
Specifies the type of request method: the type of request: GET or POST url: the server (file) location async: true (asynchronous) or false (synchronous)
send()
Sends the request to the server (used for GET)
send(string)
Sends the request to the server (used for POST)
A simple GET
request:
xhttp.open("GET", "demo_get.asp", true); xhttp.send();
xhttp.open("GET", "demo_get2.asp?fname=Henry&lname=Ford", true); xhttp.send();
Last updated
Was this helpful?