I am using mouseover event on span element to initiate an ajax post call to php page, but I always get undefined, first for responseText when I used a simple echo to get response and now when I use responseXML. Can somebody please explain me why. Here is ajax code:
var span = document.getElementsByTagName('span');
for (var i = 0; i < span.length; i++) {
span[i].addEventListener("mouseover", showInformation, false);
}
function showInformation(event) {
var xhr = new XMLHttpRequest();
xhr.open("POST", "../includes/ajax_response.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
content(xhr, event);
}
};
xhr.send("uname=" + event.target.firstChild.textContent);
}
function content(xhr, event) {
var info = document.getElementById('displayInformation');
var xmlResponse = xhr.resopnseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.data;
info.innerHTML = message;
info.style.visibility = "visible";
event.target.addEventListener("mouseout", function() {
document.getElementById('displayInformation').style.visibility = "hidden";
}, false);
}
And this is php code:
$username = $_POST['uname'];
$query = "SELECT id, joined FROM users WHERE username = '{$username}' LIMIT 1";
$first_result = Database::getInstance()->query($query);
if ($first_result->num_rows == 1) {
foreach ($first_result as $first) {
$id = $first['id'];
$joined = $first['joined'];
}
}
$first_result->free();
$query = "SELECT COUNT(message) AS count FROM blogs WHERE user_id = '{$id}'";
$results = Database::getInstance()->query($query);
if ($results) {
foreach ($results as $result) {
$number = $result['count'];
}
}
header("Content-Type: text/xml");
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
echo "joined: {$joined}";
echo "number of posts: {$number}";
echo '</response>';
This is version of php with xml, I tired simpler versions with just $username = $_POST['uname']
and then echo $username
, but always response is undefined.
I read your code once and there does not seem to be any major error. However, I found out this minor bug:
var xmlResponse = xhr.resopnseXML;
spelling of responseXML is incorrect .. maybe that's what's causing the xmlResponse to be undefined?
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments