How to Send and Receive XML Data to and from the Server
See XML: Tips and Tricks for similar articles.
In addition to the responseText property, XMLHttpRequest objects also have a responseXML property, which holds the data returned from the server as an XML document object (or null if the body content returned is not well-formed XML). Follow these eight steps to send XML data in an HTTP POST, receive an XML document from a server, and output the XML that was received.
- Create an
XMLHttpRequestobject and make a request for an XML document.var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST","books"); - Initialize a variable to hold the result of the AJAX request.
var xmlDoc; - Write code to listen for a change in the state of the
xmlhttpresponse, using theonreadystatechangeevent handler.xmlhttp.onreadystatechange = function() { //Do something here }; - Write a callback function to be called when the state changes, and use an
ifstatement to check whether the request was successful.xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { //Request was successful } }; - If the request was successful, assign the XML response to the
xmlDocvariable.xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { xmlDoc = xmlhttp.responseXML; } }; - If you want to send XML data to the server, set the Request Header correctly to be read by the sever as XML.
xmlhttp.setRequestHeader('Content-Type', 'text/xml'); - Use the
send()method to send the request, along with any XML data.var xml = "<xml><query><author>John Steinbeck</author></query></xml>"; xmlhttp.send(xml); - Output the data to see the results. Here's a complete demo that will send XML to the server, receive XML from the server, and write the XML response to the browser's JavaScript console.
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>test handle response</title> <script> var xmlhttp = new XMLHttpRequest(); xmlhttp.open("POST","books"); var xmlDoc; xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { xmlDoc = xmlhttp.responseXML; console.log(xmlDoc); } }; xmlhttp.setRequestHeader('Content-Type', 'text/xml'); var xml = "<?xml version='1.0'?><query><author>John Steinbeck</author></query>"; xmlhttp.send(xml); </script> </head> <body> </body> </html>
