How to get response data from XMLHttpRequest?


I was trying to get location by calling google maps API using javascript and wanted to know how to get response text/data after request is successfully sent.

Here is my javascript code:

if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(sendLocation);
        } else {
            alert("Geolocation is not supported by this browser.");
        }

        function sendLocation(position) {
            var latlng = { lat: position.coords.latitude, lng: position.coords.longitude };
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function (data) {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                    // need response here but data is not working
                    console.log(data)
                }
            };
            xhttp.open("POST", " http://maps.googleapis.com/maps/api/geocode/json?latlng=position.coords.latitude,position.coords.longitude&sensor=false", true);
            xhttp.send();
        }

How can I get it? Thanks


Asked by:- Sam
1
: 3178 At:- 6/13/2018 8:36:55 AM
Javascript google maps reverse geocoding







2 Answers
profileImage Answered by:- manish

You can get response text by using  XMLHttpRequest.responseText; in your javascrip code, so you modified code will be as below

function sendLocation(position) {
            var latlng = { lat: position.coords.latitude, lng: position.coords.longitude };
            var xhttp = new XMLHttpRequest();
            xhttp.onreadystatechange = function (data) {
                if (xhttp.readyState == 4 && xhttp.status == 200) {
                    //this is response data
                    console.log(xhttp.responseText;)
                }
            };
            xhttp.open("POST", " http://maps.googleapis.com/maps/api/geocode/json?latlng=position.coords.latitude,position.coords.longitude&sensor=false", true);
            xhttp.send();
        }

If you use XMLHttpRequest to get the content of a remote HTML webpage, the responseText property is a string containing the raw HTML. This could prove difficult to manipulate and analyze. There are three primary ways to analyze and parse this raw HTML string:

  1. Use the XMLHttpRequest.responseXML property as covered in the article HTML in XMLHttpRequest.
  2. Inject the content into the body of a document fragment via fragment.body.innerHTML and traverse the DOM of the fragment.
  3. RegExp can be used if you always know the content of the HTML responseTextbeforehand. You might want to remove line breaks, if you use RegExp to scan with regard to linebreaks. However, this method is a "last resort" since if the HTML code changes slightly, the method will likely fail.

Hope it helps.

3
At:- 6/13/2018 3:25:49 PM Updated at:- 9/27/2022 8:40:08 AM
Good xhttp.responseText works for me, there small typo error of semi-colon in your answer's code. 0
By : Sam - at :- 6/21/2018 6:53:46 PM


profileImage Answered by:- Vinnu

To get xmlhttprequest response in javascript, we can have multiple methods

using POST method

function createUser(){
    var request = new XMLHttpRequest();
    var params = "id=1&name=hello";

    request.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            console.log(this.responseText);
        }
    };

    request.open('POST', 'https://www.exampleworld.com/api/createUser', true);
    request.setRequestHeader('api-key', 'your-api-key');
    request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    request.send(params);
}

using GET

function readResponse(xhr) {
    var data;
    if (!xhr.responseType || xhr.responseType === "text") {
        data = xhr.responseText;
    } else if (xhr.responseType === "document") {
        data = xhr.responseXML;
    } else {
        data = xhr.response;
    }
    return data;
}

var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
    if (xhr.readyState == 4) {
        console.log(readResponse(xhr));
    }
}
xhr.open('GET', 'http://www.google.com', true);
xhr.send(null);

Using Fetch

const url = "https://example.com";
fetch(url)
  .then(
    response => response.text() // .json(), .blob(), etc.
  ).then(
    text => console.log(text) // Handle here
  );

hope it helps, thanks

1
At:- 6/22/2022 5:10:27 PM






Login/Register to answer
Or
Register directly by posting answer/details

Full Name *

Email *




By posting your answer you agree on privacy policy & terms of use