Programmer
Programmer

Reputation: 8727

PHP AJAX response in XML string

I have a web page that is making an AJAX call which echoes a XML string in below format:

<ECG>Abnormal</ECG><SP>10.99</SP><BP>120/90</BP><OXY>139</OXY><TMP>23</TMP>

AJAX call

$.ajax({
        type:'post',
        url: 'check_status.php',
        dataType: 'xml',
        success: function(xml) {
                        var ecg = $(xml).find("ECG").text(); 
                        var sp = $(xml).find("SP").text(); 
                        var bp = $(xml).find("BP").text(); 
                        var oxy = $(xml).find("OXY").text(); 
                        var tmp = $(xml).find("TMP").text(); 
                        alert(tmp);
        },
        error: function(){
                        alert('Error');
                        update();
        }
        });

The XML response is simply created by PHP backend script by constructing the XML string:

$resp = "<ECG>" . $ecg . "</ECG>" ....
echo $resp;

But still the alert in the AJAX error method is called - is there something else that I need to do from backend script.

Upvotes: 1

Views: 65

Answers (1)

hek2mgl
hek2mgl

Reputation: 158250

As I told in comments, the response isn't well formed XML. You're missing a document node which wraps the other nodes. Like this:

<?xml version="1.0"?>
<RESPONSE>
  <ECG>Abnormal</ECG>
  <SP>10.99</SP>
  <BP>120/90</BP>
  <OXY>139</OXY>
  <TMP>23</TMP>
</RESPONSE>

Also you are encouraged to set the proper content type header from PHP:

header('Content-Type: text/xml');

(before the output)

Upvotes: 1

Related Questions