Wesley De Keirsmaeker
Wesley De Keirsmaeker

Reputation: 1025

XMLHttpRequest.responseXML returns NULL from Ajax to .php page

I have a search box where people can fill in an ID. If they push the button next to it, I have a ajax request to a php file that takes the ID, finds related information in a DB and should return as an XML page.

loadContact.php

<?php
header("Content-type: application/xml"); 
include('../classes/php.php');
$contactID = $_POST["contactID"];
$mItemArray = getItemFromID($contactID);
echo "
<?xml version=\"1.0\" encoding=\"utf-8\" ?> 
<app naam=\"send-to-work\" id=\"50029154\">
<contact id=\"" . $contactID . "\">
    <team>" . $mItemArray['Team'] . "</team> 
    <role>" . $mItemArray['Role'] . "</role> 
    <name>" . $mItemArray['Name'] . "</name> 
    <firstname>" . $mItemArray['Fname'] . "</firstname> 
    <phone>" . $mItemArray['Phone'] . "</phone> 
    <email>" . $mItemArray['Email'] . "</email> 
</contact>
</app>
";
?>

js.js

function loadContact()
{
var xmlhttp;
var x;
var contactID = $("input#id").val();
if (contactID != "" && contactID == parseInt(contactID)){
    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    } else  {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange=function()
    {
        if (xmlhttp.readyState==4 && xmlhttp.status==404)
        {
            alert("PAGE NOT FOUND");
        }
        if (xmlhttp.readyState==4 && xmlhttp.status==200)
        {
           try{
            x=xmlhttp.responseXML   ;
           }
           catch(error){
               alert("error " + error);
           }
            alert(x);
            alert(xmlhttp.getResponseHeader("Content-Type"));
        }
    }
    xmlhttp.open("POST","ajax/loadContact.php",true);
    xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); 
    xmlhttp.send("contactID="+contactID);
}
}

What I currently got with this is:

x = null
xmlhttp.getResponseHeader("Content-Type") = application/xml.
xmlhttp.responseText //returns the correct page with the correct data. 
xmlhttp.open("POST","test.xml",true) //DOES set the responseXML as x = [object Document]

So I'm a little lost. It is regonized as an application/xml file, but the XMLHttpRequest only sets the responseText and not the responseXML.

Could anyone explain me what I'm not seeing. Thanks on beforehand!

Upvotes: 0

Views: 6208

Answers (1)

Wesley De Keirsmaeker
Wesley De Keirsmaeker

Reputation: 1025

I'm sorry guys. I was looking for this problem for 2 hours, just went to the bathroom and tested it in an other way.

The problem was in my PHP file:

echo "
<?xml version=\"1.0\" encoding=\"utf-8\" ?> 

doesn't work because the XML declaration(?) should be on the first line.

echo "<?xml version=\"1.0\" encoding=\"utf-8\" ?> 

does work.

Upvotes: 2

Related Questions