bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Objects, Classes, and Advanced Patterns
JavaScript•Objects, Classes, and Advanced Patterns

AJAX - The XMLHttpRequest Object

Concept visual

AJAX - The XMLHttpRequest Object

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

The keystone of AJAX is the XMLHttpRequest object.

Create an XMLHttpRequest object

Define a callback function

Open the XMLHttpRequest object

Send a Request to a server

The XMLHttpRequest Object

All modern browsers support the

XMLHttpRequest object.

The

XMLHttpRequest object can be used to exchange data with a web server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object

Formula

All modern browsers (Chrome, Firefox, IE, Edge, Safari, Opera) have a built - in

XMLHttpRequest object.

Syntax for creating an

XMLHttpRequest object:

variable

= new XMLHttpRequest();

Define a Callback Function

A callback function is a function passed as a parameter to another function. In this case, the callback function should contain the code to execute when the response is ready.

xhttp.onload = function() {

// What to do when the response is ready

}

Send a Request

To send a request to a server, you can use the open() and send() methods of the

XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Example

// Create an XMLHttpRequest object const xhttp = new XMLHttpRequest();
// Define a callback function xhttp.onload = function() {

// Here you can use the Data

}
// Send a request xhttp.open("GET", "ajax_info.txt");
xhttp.send();

Access Across Domains

For security reasons, modern browsers do not allow access across domains. This means that both the web page and the XML file it tries to load, must be located on the same server. The examples on W3Schools all open XML files located on the W3Schools domain. If you want to use the example above on one of your own web pages, the XML files you load must be located on your own server.

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()

Previous

AJAX Introduction

Next

AJAX - XMLHttpRequest