Blog Tags

Lab Eleven Blogs

A short description about your blog
Tags >> Ajax

Parsing an XML string retrieved using AJAX

Posted by: twmeier

Tagged in: XML , Programming , PHP , Javascript , Ajax

While working on an AJAX function this week, I found the need to parse an XML string using JavaScript and PHP. The following JavaScript was used to retrieve an XML string from a PHP file:

function someJavascriptFunction() {
      url = "/components/com_component/ajax/ajax.php?task=someTask";    
      url += "&cc_number="+document.getElementById('cc_number').value;"GET",url,true);    
      xmlHttp.onreadystatechange = function() {
      if (xmlHttp.readyState == 4)  {       
           var response = xmlDoc.getElementsByTagName("response")[0].childNodes[0].nodeValue;
           document.getElementById("someID").innerHTML = response;

function GetXmlHttpObject()    {
      var xmlHttp=null;
      try {
           // Firefox, Opera 8.0+, Safari
           xmlHttp=new XMLHttpRequest();
      catch (e) {
           //Internet Explorer
           try {
                xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
           catch (e) {
                xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
      return xmlHttp;

As you can see from the code above, the XML field I was interested in was the "response" field. The XML string that was created and passed using xmlHttp.responseText from the PHP file looked similar to this:

      <message>Some Message</message>
      <response>Some Message</response>

Not only did I need to parse the XML from the  responseText in javascript, but I also need to parse it inside the PHP function that the JavaScript function called. The XML above was retrieved from a payment gateway in the PHP function using CURL and naned $xmlString.

The only field I needed in the PHP file was the "message" field, and to retrieve it, (or any other field), I did the following in the PHP file:

$xml = new SimpleXMLElement($xmlString);
$message = $xml->authorizationResponse->message;

Don't forget you still need to echo out the entire XML string in your PHP file order to be used by your JavaScript function:

echo $xmlString;

Latest Blogs

Fix Bad Credit With These Helpful Tips
Feb 26th 2013 by: Administrator

Will iPhone Apps Run On iPad?
Jan 29th 2010 by: Trevor M.

How to create a marquee text for an iPhone app
Jan 21st 2010 by: Trevor M.

How to Submit Additional Images in Virtuemart
Aug 7th 2009 by: Trevor M.

Using an Image as a Submit Button in HTML
Jul 31st 2009 by: Trevor M.

Read all blogs