Search code examples
javascriptxmlhttprequest

Javascript XMLHttprequest returns empty from WSDLL webservice


I have made a wsdll webservice witch runs local on my server. And I am getting the xml responses in the browser when I run it.

Now I am trying to get that data via javascript, but my request does readyState 1 and then 4, witch of course give an empty result, but I can't seem to see where my error is.

I have tried running Chrome in --allow-file-access-from-files, but did't help.

The code

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>

<body>
<script type="application/javascript">
    function start(){
        var c = loadXMLDocPost("http://picture.zaqsolutions.com/picture/picture.asmx/getMeetingPicture?MeetingID=46");
        alert(c);
        var t = c.getElementsByTagName('name')[0].childNodes[0].nodeValue;
    }

    function loadXMLDocPost(filename) {
        var xhttp;
        xhttp = new XMLHttpRequest();
        xhttp.open("GET",filename,true);
        xhttp.send();
        return xhttp.responseXML;
    }
    </script>
<button id="test" onClick="start()">Test</button>
</body>
</html>

I would appreciate of any got an idea why.


Solution

  • You are trying to read the HTTP response immediately after instructing the browser to send the request. This is before the response has arrived.

    You need to wait for it to load (by using an event listener) and then read the data.

    var xhttp;
    xhttp = new XMLHttpRequest();
    xhttp.open("GET",filename,true);
    xhttp.addEventListener("load", process_response);
    xhttp.send();
    
    function process_response() {
        var data = this.responseXML;
        alert(data);
    }