Search code examples
javascriptxmlapiresponse

How to parse XML response from API in JavaScript?


I am working with this API, which returns flight statuses originating in LHR to MAN (just an example). The response is formatted as XML, but I'm having trouble reading it with JavaScript.

I tried the following:

function loadXMLDoc(dname) { //the dname here is the url
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    } else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET", dname, false);
    xhttp.send();
    return xhttp.responseXML;
}

But it doesn't work. Is there another way to read the XML response of the API?


Solution

  • You could use jQuery and then make your ajax call using jQuery.ajax()

    The code might look something like this...

        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: url,
            data: JSON.stringify(data),
            dataType: "json",
            error: function (response) {
                alert('Error: There was a problem processing your request, please refresh the browser and try again');
            },
            success: function (response) {
                if (response !== undefined && response !== null) {
                   /* Evaluate the SOAP response object here */
                }
            }
        });