0

I'm trying to make a function that sends an XMLHttpRequest and return a string with the contents of the response, but it always returns null. How do I fix this?

Code:

function getPage() {
    if (window.XMLHttpRequest)
    {
        xmlhttp=new XMLHttpRequest();
    }
    else
    {
        xmlhttp=new ActiveXObject('Microsoft.XMLHTTP');
    }
    xmlhttp.open('GET','page.php',false);
    xmlhttp.send();
    xmlDoc = xmlhttp.responseXML;
    if ($.browser.msie) return xmlDoc.xml;
    else return (new XMLSerializer()).serializeToString(xmlDoc);
}
4
  • 1
    Question 1: What browser are you using? There are two different code paths. Question 2: Since it seems you're using JQuery, why not use $.get()? Commented Apr 2, 2011 at 17:15
  • I use $.ajax() in jQuery because it gives more options. Then you can just have a listener for success, completed, and error and see what your problem is. Commented Apr 2, 2011 at 17:22
  • 1
    I am using jQuery. Actually, I could have just used xmlhttp.responseText instead of xmlhttp.responseXML. Is $.get() asynchronous? Commented Apr 2, 2011 at 17:23
  • 1
    xmlhttp.responseText should always return the contents of the response, while xmlhttp.responseXML will only return if the response is xml. Try logging responseText to see with the response actually is; it could be that its not xml. Commented Apr 3, 2011 at 3:10

1 Answer 1

0

If you are using Internet Explorer, at least, then you may have a null response because the ContentType header in the response is missing or incorrect. Quoting Microsoft's documentation on the responseXML property:

If the ... Multipurpose Internet Mail Extension (MIME) type was not correctly set to one of the supported MIME types ... then responseXML will be empty.

The supported MIME types for MSXML 6.0 are: "text/xml", "application/xml" or anything that ends with "+xml", for example "application/rss+xml".

The supported MIME types for versions prior to MSXML 6.0 are: "text/xml", "application/xml".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.