XMLHttpRequest QML Type

Object for sending requests to a server. More...

Import Statement: import QtQml



Detailed Description

The XMLHttpRequest object allows scripts to perform HTTP client functionality, such as submitting form data or loading data asynchronously from a server.

The XMLHttpRequest API is a partial implementation of the W3C XHR Level 1 standard with the following exception:

  • It does not enforce the same origin policy.

Sending requests

Use the following steps to send a request using the XMLHttpRequest API:

  1. Create a XMLHttpRequest object.
  2. Assign a callback function to the onreadystatechange signal handler.
  3. Call open() with the appropriate HTTP method and URL to request.
  4. Call send()

The callback function handles the HTTP response for a request. It's a good practice to check if the readyState is DONE in the handler, before you use one of the following methods to read the response:

The following example demonstrates how to send a request and read the response:

import QtQuick
import QtQuick.Layouts
import QtQuick.Controls
import "request.js" as XHR

ApplicationWindow {
      width: 640
      height: 640
      visible: true

      ColumnLayout {
           anchors.fill: parent

           RowLayout {
               Layout.fillWidth: true

               TextField {
                   id: urlTextField
                   text: "https://www.example.com/index.html"
                   Layout.fillWidth: true
               Button {
                   text: qsTr("Send!")
                   onClicked: XHR.sendRequest(urlTextField.text, function(response) {
                       statusTextField.text = response.status;
                       let isPlainText = response.contentType.length === 0

                       contentTypeTextField.text = isPlainText ? "text" : response.contentType;

                       if (isPlainText)
                           contentTextArea.text = response.content;

           GridLayout {
               columns: 2

               Layout.fillWidth: true

               Label {
                   text: qsTr("Status code")

                   Layout.fillWidth: true
               Label {
                   text: qsTr("Response type")

                   Layout.fillWidth: true
               TextField {
                    id: statusTextField

                    Layout.fillWidth: true
               TextField {
                    id: contentTypeTextField

                    Layout.fillWidth: true
           Flickable {
               clip: true
               contentWidth: contentTextArea.width
               contentHeight: contentTextArea.height
               Text {
                    id: contentTextArea

               Layout.fillWidth: true
               Layout.fillHeight: true
               ScrollBar.vertical: ScrollBar {}
               ScrollBar.horizontal: ScrollBar {}

The earlier snippet connects the button's clicked signal to an external sendRequest function. A resource URL is passed as the first argument, and a callback function to handle UI updates is passed as the second. The sendRequest function, which exists in an external request.js file, can be implemented like this:

function sendRequest(url, callback)
    let request = new XMLHttpRequest();

    request.onreadystatechange = function() {
        if (request.readyState === XMLHttpRequest.DONE) {
            let response = {
                status : request.status,
                headers : request.getAllResponseHeaders(),
                contentType : request.responseType,
                content : request.response


    request.open("GET", url);

The earlier snippet follows the four simple steps mentioned at the beginning. It instantiates the XMLHttpRequest object first, and assigns a callback function to handle the response. It also calls open() with an HTTP method and URL, before it sends the request to the server. Notice that the second argument to sendRequest is called at the end of onreadystatechange, in order to handle UI updates based on the HTTP response.

Set the QML_XHR_DUMP environment variable to 1 if you want to debug a request. This will log the following information:

  • Method type (GET or POST), URL, and body of sent requests.
  • URL and body of responses received.
  • Network error, if any.

Accessing local files

By default, you cannot use the XMLHttpRequest object to read files from your local file system. If you wish to use this feature to access local files, you can set the following environment variables to 1.


Warning: Use this feature only if you know that the application runs trusted QML and JavaScript code.

responseXML document

The responseXML XML DOM tree currently supported by QML is a reduced subset of the DOM Level 3 Core API supported in a web browser. The following objects and properties are supported by the QML implementation:

  • nodeName
  • nodeValue
  • nodeType
  • parentNode
  • childNodes
  • firstChild
  • lastChild
  • previousSibling
  • nextSibling
  • attributes
  • xmlVersion
  • xmlEncoding
  • xmlStandalone
  • documentElement
  • tagName
  • name
  • value
  • ownerElement
  • data
  • length
  • isElementContentWhitespace
  • wholeText

Property Documentation

onreadystatechange : function

Choose a callback function you want to get invoked whenever the readyState of the XMLHttpRequest object changes.

See also readyState.

[read-only] readyState : enumeration

Indicates the current state of the XMLHttpRequest object.

The value can be one of the following:

XMLHttpRequest.UNSENTThe request is not initialized, which is the state before calling open().
XMLHttpRequest.OPENEDThe request is initialized, meaning open() was previously called, but no further progress.
XMLHttpRequest.HEADERS_RECEIVEDReceived a reply from the sever, but the request is not fully processed yet.
XMLHttpRequest.LOADINGDownloading data from the server.
XMLHttpRequest.DONEFinished processing the request.

See also onreadystatechange.

[read-only] response : var

Returns either a String, an ArrayBuffer, or a Document, depending on the responseType of the last request.

See also responseType, responseText, and responseXML.

[read-only] responseText : string

Returns a String containing the data received from the last response.

See also responseXML.

responseType : string

Returns a String describing the content type of the last response received.

  • If the response type is "text" or an empty String, the response content is a UTF-16 encoded String.
  • If the response type is "arraybuffer", it means that the response content is an ArrayBuffer containing binary data.
  • If the response type is "json", the response content should be a JSON Document.
  • If the response type is "document", it means that the response content is an XML Document, which can be safely read with the responseXML property.

See also response.

[read-only, since 6.6] responseURL : string

Returns the url that was used to retrieve the response data, after any redirects have occurred.

This property was introduced in Qt 6.6.

[read-only] responseXML : var

Returns either a Document, or null, if the response content cannot be parsed as XML or HTML. See the responseXML document section for more information.

See also responseText.

[read-only] status : int

Returns the status code for the last response received.

See also statusText.

[read-only] statusText : string

Returns a String that has the status message associated with the status code for the last response received.

See also status.

Method Documentation

void abort()

Cancels the current request.

It changes the readyState property to be XMLHttpRequest.UNSENT and emits the readystatechange signal.

string getAllResponseHeaders()

Returns a String of headers received from the last response.

The following is an example response header:

content-encoding: gzip
content-type: text/html; charset=UTF-8
date: Mon, 06 Feb 2023 09:00:08 GMT
expires: Mon, 13 Feb 2023 09:00:08 GMT
last-modified: Thu, 17 Oct 2019 07:18:26 GMT

See also getResponseHeader().

string getResponseHeader(headerName)

Returns either the headerName value from the last response, or an empty String, if the headerName is missing.

See also getAllResponseHeaders().

void open(method, url, async)

Specify the HTTP method you want the request to use, as well as the url you wish to request. You should make sure to always call this function before send(). An optional third parameter async can be used to decide whether the request should be asynchronous or not. The default value is true.

Emits the readystatechange signal, which calls the onreadystatechange handler with the readyState property set to XMLHttpRequest.OPENED.

[since 6.6] void overrideMimeType(mime)

Forces the XMLHttpRequest to interpret the data received in the next HTTP response, as if it had the MIME type mime, rather than the one provided by the server.

This method was introduced in Qt 6.6.

void send(data)

Sends the request to the server. You can use the optional argument data to add extra data to the body of the request. This can be useful for POST requests, where you typically want the request to contain extra data.

The readyState property is updated once a response has been received from the server, and while the response is being processed. It will first be set to HEADERS_RECEIVED, then to LOADING, and finally DONE, once the response has been fully processed. The readystatechange signal is emitted every time readyState is updated.

void setRequestHeader(header, value)

Adds a new header to the next request you wish to send. This is a key-value pair, which has the name header and the corresponding value.

© 2024 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.