Send an HTTP request asynchronously with javascript & return the response

In this example we'll send a request to an endpoint, parse the response and load it into an HTML element

Rob Johnson

By Rob Johnson

Mon Apr 18 2022

Hey, looks like you're accessing this page from IP waiting...

Here's some javascript that reaches out to a free IP lookup service called, ipify.org (open source). The code execution is done asynchronously, which means that the javascript doesn't hold up the page from loading.

You can see this async call in action by reloading the page quickly and seeing the IP address above flicker with the text waiting.... You can also disable javascript in your browser to see the message.

Async calls are a good way to speed up the page if your page isn't dependent on the javascript executing immediately.

In the below code we make the request asynchornously, get response (JSON), parse the JSON and load it into a code element with the ID of your-ip.

// create the new object
let request = new XMLHttpRequest()
// define the response variable to store the object with the JSON already parsed
let response = []
// make a request with json as the response format
request.open('GET', 'https://api.ipify.org?format=json', true) // set true for asynchronous
request.setRequestHeader('Accept', 'application/json')


request.onreadystatechange = function () {
  if (this.readyState === 4 && this.status === 200) {
    // result will be json
    // example: {"ip":"127.0.0.1"}
    // parse the json via JSON.parse
    response = JSON.parse(this.responseText)
    // insert the value of the key "ip"
    document.getElementById('your-ip').innerHTML = response.ip
  }
};
// send back the response object
request.send(response)

On line 11 of the code above we're requesting a this.readyState of 4 which means that the request is finished and response is ready.

We're also making sure that the this.status is 200 which means that the request has succesfully completed.

XMLHttpRequest.readyState

this.readyState holds the status of the XMLHttpRequest which has the following responses:

Code Description
0 Request not initialized
1 Server connection established
2 Request received
3 Processing request
4 Request finished and response is ready

Learn more about XMLHttpRequest.readyState

HTML response status codes

Every HTTP request has an HTML response status code that provides information about the response.

Code Range Description
100-199 Informational responses
200299 Successful responses
300399 Redirection messages
400499 Client error responses
500599 Server error responses

Learn more about HTML response status codes


Going a step further

ipify.org is a good free solution to get the IP address only, however there are services that offer much more information.

ipdata offers an API that provides a lot of information from an IP. Here's an example of the response:

{
    "ip": "127.0.0.1",
    "is_eu": false,
    "city": "Seattle",
    "region": "Washington",
    "region_code": "WA",
    "country_name": "United States",
    "country_code": "US",
    "continent_name": "North America",
    "continent_code": "NA",
    "latitude": 47.6080,
    "longitude": -122.3351,
    "postal": "98101",
    "calling_code": "1",
    "flag": "https://ipdata.co/flags/us.png",
    "emoji_flag": "\ud83c\uddfa\ud83c\uddf8",
    "emoji_unicode": "U+1F1FA U+1F1F8",
    "asn": {
        "asn": "AS33650",
        "name": "Comcast Cable Communications, LLC",
        "domain": "xfinity.com",
        "route": "127.0.0.0/17",
        "type": "isp"
    },
    "company": {
        "name": "Comcast Cable Communications, Inc. ",
        "domain": "xfinity.com",
        "type": "isp"
    },
    "languages": [
        {
            "name": "English",
            "native": "English",
            "code": "en"
        }
    ],
    "currency": {
        "name": "US Dollar",
        "code": "USD",
        "symbol": "$",
        "native": "$",
        "plural": "US dollars"
    },
    "time_zone": {
        "name": "America/Los_Angeles",
        "abbr": "PDT",
        "offset": "-0700",
        "is_dst": true,
        "current_time": "2022-04-19T02:44:50-07:00"
    },
    "threat": {
        "is_tor": false,
        "is_icloud_relay": false,
        "is_proxy": false,
        "is_datacenter": false,
        "is_anonymous": false,
        "is_known_attacker": false,
        "is_known_abuser": false,
        "is_threat": false,
        "is_bogon": false,
        "blocklists": []
    },
    "count": "4"
}

You can sign up for free and get 1500 calls per day for non-commercial use. Pricing tiers grant access to commercial blocklists and VPN detection.

Here's a description of all of the response fields.

let request = new XMLHttpRequest()
let response = []

request.open('GET', 'https://api.ipdata.co/?api-key=your-api-key-here')
request.setRequestHeader('Accept', 'application/json')
request.onreadystatechange = function () {
  if (this.readyState === 4 && this.status == 200) {
    response = JSON.parse(this.responseText)
  }
};
request.send(response)

These values can then be accessed by response.ip or response.company.name for example.

Click for a live demo



# commerce 14 # seo 5 # tools 6 # amazon 1 # sql 4 # shopify 9 # javascript 13 # projects 4 # css 2 # git 2 # php 3 # analytics 4 # api 6 # monitoring 2 # python 2 # aws 2