How responseText and responseXML Work in AJAX

Introduction to Ajax

8. responseText and responseXML server responses

Using responseText and responseXML determines if the server responses in AJAX are in XML or plain text.  The field in which the response is returned depends upon what format is being used.  To determine the format, the programmer must either know what the server side script is set up to return or test the content type in the code.

responseText

The responseText property, which was introduced with Windows Internet Explorer 7, is used if the response from the server is not XML.  It has no default value and the response body is a string.

responseXML

To receive a response body in an XML formatted text, use responseXML to parse the response as an XML object.  This property also has no default value and is compatible with Windows Internet Explorer 5, 7, 8, and 9.  In Internet Explorer 10 in Windows 8, the responseXML property is updated from XMLHttpRequest to return a native XML document by default.

Example

The following code fragment illustrates these two fields by substituting alerts to display the appropriate field into the code, which was from the previous tutorial where the content type was tested.

if (cType == 'text/xml') {
alert(this.responseXML);
} else if (cType == 'text/plain') {
alert(this.responseText);
} else {
alert('unknown content type');
}

Format
mla apa chicago
Your Citation
Dominy, Robert. "How responseText and responseXML Work in AJAX." ThoughtCo, Jul. 7, 2015, thoughtco.com/how-responsetext-and-responsexml-work-in-ajax-2037563. Dominy, Robert. (2015, July 7). How responseText and responseXML Work in AJAX. Retrieved from https://www.thoughtco.com/how-responsetext-and-responsexml-work-in-ajax-2037563 Dominy, Robert. "How responseText and responseXML Work in AJAX." ThoughtCo. https://www.thoughtco.com/how-responsetext-and-responsexml-work-in-ajax-2037563 (accessed November 20, 2017).