0

I am new to Javascripting. I have http webservice URL which results in xml respose. how do I get the response xml from the URL. I tried using the following using XMLHttpRequest but no luck.

function send_with_ajax( the_url ){
    var httpRequest = new XMLHttpRequest();
    //httpRequest.onreadystatechange = function() { alertContents(httpRequest); };  
    httpRequest.open("GET", the_url, true);
    httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    httpRequest.setRequestHeader("X-Requested-With", "XMLHttpRequest");
    httpRequest.setRequestHeader("X-Alt-Referer", "http://www.google.com");
    httpRequest.send();
    httpRequest.onreadystatechange = function() { 
        if (httpRequest.readyState == 4)
        {
            var _tempRecommendations = httpRequest.responseXML;
            window.alert(httpRequest.response)
            window.alert(httpRequest.responseText)
            window.alert(_tempRecommendations)
        }
    };  
};

I always get httpRequest.readyState = 1 and also when I evaluate the response in console its all null.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Karthick
  • 675
  • 4
  • 12
  • 24

1 Answers1

0

According to this: Ajax won't get past readyState 1, why?, you should try to replace your onreadystatechange event by an onload event:

httpRequest.onload= function() { 
        if (httpRequest.readyState == 4)
        {
            var _tempRecommendations = httpRequest.responseXML;
            window.alert(httpRequest.response)
            window.alert(httpRequest.responseText)
            window.alert(_tempRecommendations)
        }
    };  

If it doesn't work, try to simplify your code, start with a very basic request like shown here: http://www.w3schools.com/xml/xml_parser.asp for example. Then start adding request headers, to see which instructions break your program. You can also check the webservice by calling it directly in the browser to make sure that the problem comes from your side

Community
  • 1
  • 1
Antoine
  • 2,785
  • 1
  • 16
  • 23
  • When I try to load I get the following error: XMLHttpRequest cannot load http://. Origin https:// is not allowed by Access-Control-Allow-Origin. – Karthick May 31 '13 at 06:14
  • So the issue doesn't come from your side but from the server, which doesn't allow ajax requests. You need to add a "Access-Control-Allow-Origin" header to the server response. More information here: http://stackoverflow.com/questions/10143093/origin-is-not-allowed-by-access-control-allow-origin?answertab=active#tab-top If you don't have access to the server, you should look for information about jsonp requests – Antoine May 31 '13 at 06:21