xmlDocumentElement is not defined - php

Here is my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onLoad="process()">
<h3>WELCOME to our online food store</h3>
Please type what you want to order:
<input type="text" id="userinput" ></input>
<div id="underInput"></div>
</body>
</html>
PHP
<?php
header('Content-Type: text/xml');
echo"<?xml version='1.0' encoding='UTF-8' standalone='yes'?>";
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','loaf','mutton');
if(in_array($food,$foodArray))
echo 'We do have'.' '.$food;
elseif($food=='')
echo 'type something dude!';
else
echo 'Sorry we dont sell'.' '.$food;
echo '</response>';
?>
JS
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else if(window.XMLHttpRequest)
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert('cannot connect to database!');
}
else
{
return xmlHttp;
}
}
function process()
{
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
{
food = encodeURIComponent(document.getElementById("userinput").value);
xmlHttp.open("GET", "ajax.php?food=" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeOut('process()',1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumnetElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHtml = "<span style='color:blue'" + message + "</span>";
setTimeOut('process()',1000);
}
}
else
{
alert('something went wrong');
}
}
Everything seems to be fine to me but I still keep getting the error 'xmlDocumentElement is not defined'. Seems like this is an error due to some parsing issues within javascript and php.. Please help me fix this error. thanks

try to use
window.setTimeOut('process', 1000);

Related

AJAX document.getElementById not working when pass through parameters

I'm writing an AJAX code that gets input from the users, and outputs the results, and it works when I'm setting the variable called text inside the function, but when I'm passing it through it doesn't work. Please take a look, I've taken all the irrelevant codes out, so it's short.
Code when I'm not passing it through the parameter:
<script type = "text/javascript">
function process(){
text = 'userInput';
food = encodeURIComponent(document.getElementById(text).value);
}
</script>
<html>
<body onload="process()">
</body>
</html>
Code when I'm passing it through the parameter:
<script type = "text/javascript">
function process(text){
food = encodeURIComponent(document.getElementById(text).value);
}
</script>
<html>
<body onload="process('userInput')">
</body>
</html>
I did document.write both times to make sure that the variable is really 'userInput', and both times, whether I'm passing it through or setting it inside the function, it printed out fine, so I'm not sure what the problem is. If you know what's wrong, please let me know. Thank you.
The whole code:
functions.js:
var xmlHttp = createXmlHttpRequestObject();
//****************************************************************AJAX
function createXmlHttpRequestObject() {
var xmlHttp;
if (window.ActiveXObject) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
xmlHttp = false;
}
} else {
try {
xmlHttp = new XMLHttpRequest();
} catch (e) {
xmlHttp = false;
}
}
if (!xmlHttp)
alert("Not xmlHttp!")else
return xmlHttp;
}
//****************************************************************AJAX
function process(IDName, passTo, output) {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
get = encodeURIComponent(document.getElementById(IDName).value);
xmlHttp.open("GET", passTo + get, true);
xmlHttp.onreadystatechange = handleServerResponse(output);
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
//****************************************************************AJAX
function handleServerResponse(output) {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById(output).innerHTML = message;
setTimeout('process()', 1000);
} else {
alert('xmlHttp.status does not equal 200!');
}
}
}
foodstore.php:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','ham');
if(in_array($food,$foodArray))
echo 'We do have '.$food.'!';
elseif ($food=='')
echo 'Enter a food';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
test5.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<body onload="process('userInput','foodstore.php?food=','underInput')">
<h3>The Chuff Bucker</h3>
Enter the food you would like to order:
<input type="text" id="userInput" />
<div id="underInput" />
</body>
</html>
I just ran this test on your (modified) code and it worked as expected.
<script type = "text/javascript">
function process(text){
alert(text);
food = encodeURIComponent(document.getElementById(text).value);
alert(food);
}
</script>
<html>
<body onload="process('userInput')">
<input id="userInput" value="yummy" />
</body>
</html>
You're performing handleServerResponse(output); when you assign the onreadystatechange handler, not when the event occurs. You need to delay calling the function until the event occurs:
xmlHttp.onreadystatechange = function() {
handleServerResponse(output);
};

Make an error to pop-up without refresh

I have this php code, which basically checks if the e-mail is correct and if it is, it saves the e-mail in a *.txt file (I'm using it for a subscribe form), if it's not it pop-ups an error div, but it pops it up with refreshing the whole web page, and when it's in the bottom you have to scroll to actually see the error.
<?php
if ( isset($_POST['submit']) ) {
if( isset($_POST['inputEmail']) ) {
$email = trim($_POST['inputEmail']);
if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<div class='wrong'>This e-mail is invalid.</div>";
}
else {
$data = $email . "\n";
$ret = file_put_contents('emailAddresses.txt', $data, FILE_APPEND | LOCK_EX);
if ( $ret !== FALSE ) {
header('Location: thanks.html');
exit;
}
}
}
}
?>
What you want to do is send your request with AJAX using javascript or jQuery.
With JavaScript:
<script type="text/javascript">
function loadXMLDoc() {
var xmlhttp;
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 ) {
if(xmlhttp.status == 200){
//Request worked, Do something
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", "ajax_info.txt", true);
xmlhttp.send();
}
</script>
With jQuery:
$.ajax({
url: "test.php",
context: document.body,
success: function(){
$(this).addClass("done");
}
});

Cannot read property 'readyState' of undefined

spend hours to find what has gone wrong, but failed.. since I'm new to Ajax, so I've no idea what I'm seeing. really need you guys to find the bug.
HTML
<!doctype html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The Chuff Bucket</h3>
Enter the food you would like to order:
<input type="text" id="userInput">
<div id="underInput" />
</body>
</html>
javascript :
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXobject){
try{
xmlHttp = new ActiveXobject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}else{
try{
xmlHttp = new XmlHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp){
alert("can't create that object");
}
else{
return xmlHttp;
}
}
function process(){
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET", "foodstore.php?food=" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = "<span style='color:blue'>" + message + "</span>";
setTimeout('process()', 1000);
}else{
alert('something went wrong');
}
}
}
PHP (I think this file caused the problem)
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','ham');
if(in_array($food,$foodArray)){
echo 'We do have ' .$food. '!';
}else if($food == ''){
echo 'Enter a food name.';
}else
{
echo "no, we don't sell " .$food. "!";
}
echo '</response>';
?>
JavaScript is case sensitive. You've got some syntax errors due to improper casing on some of the objects you're trying to create:
ActiveXobject
should be
ActiveXObject
^
and
XmlHttpRequest
should be
XMLHttpRequest
^^
The end result is that you're trying to create things that don't exist, resulting in the xmlHttp variable that is always false or undefined.
Your object creation logic seems backward (should try to create the modern object when you can, do the IE thing only if necessary), and mis-capitalized.
Try:
if (window.XMLHttpRequest) {
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
xmlHttp = false;
}
} else {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}

Search data from array in php

I want to get data from php array and show it on same page. how to
import data from php array by using search box. This code not working properly.
What is th error of this code?
foodstore.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
} else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("cant create that object hoss!");
else
return xmlHttp;
}
function process(){
if(xmlHttp.readyState==0|| xmlHttp.readyState==4){
food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET","foodstore.php?food="+food,true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML ='<span style="color:blue">'+message+'</span>';
setTimeout('process',1000);
}else{
alert('Something went wrong!');
}
}
}
foodstore.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food,$foodArray))
echo 'We do have '.$food'!';
elseif($food =='')
echo 'Enter a food you want to buy';
else
echo 'Sorry we don't sell it '.$food'!';
echo '</response>';
?>
Index.html
<html><head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The foods </h3>
Order your foods:
<input type="text" id="Userinput"></input>
<div id="underInput"></div>
</body>
</html>
How to show array data by searching from search box
I have changed the code using jquery its simple . You can try it.
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(function()
{
$("#Userinput").keyup(function()
{
process();
});
$("#Userinput").keydown(function()
{
process();
});
$("#Userinput").focus(function()
{
process();
});
$("#Userinput").change(function()
{
process();
});
});
function process() {
var input_food = $("#Userinput").val();
$.ajax({
type: "GET",
url: "foodstore.php",
data: {food: input_food},
success: function(message)
{
$("#underInput").html('<span style="color:blue">' + message + '</span>');
},
error: function()
{
$("#underInput").html('<span style="color:red">Some error occured</span>');
}
});
}
</script>
</head>
<body >
<h3>The foods </h3>
Order your foods:
<input type="text" id="Userinput" ></input>
<div id="underInput"></div>
</body>
</html>
foodstore.php
<?php
if (!empty($_GET['food']))
{
$food = $_GET['food'];
$foodArray = array('tuna', 'bacon', 'beef', 'loaf', 'ham');
if (in_array($food, $foodArray))
echo "We do have " . $food . "!";
elseif ($food == '')
echo "Enter a food you want to buy";
else
echo "Sorry we don't sell it " . $food . "!";
}
else
{
echo "Enter a food you want to buy";
}
?>
I think its simple if you know jquery .And there was a simple error in php you did't escape the extra single quotes in (don't) so I used double quotes for echo statements. Copy paste and tell if this is it what you want or not.Got any doubt ask.

PHP and AJAX onclick redirection

I am using Ajax to populate a drop down menu from the database, my question is how do I onclick redirect it to a page along with the CARD_ID i got back from the database?
right now when I click on it it's displaying the card name in the search bar which is part of what I want but now I need the other half the redirection. How can I achieve this?
<?php
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$str = $_GET['content'];
if(strlen($str))
{
$sel = mysqli_query($mysqli, "select CARD_NAME, CARD_ID,CARD_TYPE from cards where CARD_NAME like '".trim($str)."%'");
if(mysqli_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysqli_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysqli_fetch_array($sel))
{
$card_info = str_ireplace($str,"<b>".$str."</b>",($row['CARD_NAME']));
$card_type = str_ireplace($str,"<b>".$str."</b>",($row['CARD_TYPE']));
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\" onClick=\"display('".$row['CARD_NAME']."');\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
the javascript.
subject_id = '';
function handleHttpResponse() {
if (http.readyState == 4) {
if (subject_id != '') {
document.getElementById(subject_id).innerHTML = http.responseText;
}
}
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
function getScriptPage(div_id,content_id)
{
subject_id = div_id;
content = document.getElementById(content_id).value;
http.open("GET", "script_page.php?content=" + escape(content), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
if(content.length>0)
box('1');
else
box('0');
}
function highlight(action,id)
{
if(action)
document.getElementById('word'+id).bgColor = "#C2B8F5";
else
document.getElementById('word'+id).bgColor = "#F8F8F8";
}
function display(word)
{
document.getElementById('text_content').value = word;
document.getElementById('box').style.display = 'none';
document.getElementById('text_content').focus();
}
function box(act)
{
if(act=='0')
{
document.getElementById('box').style.display = 'none';
}
else
document.getElementById('box').style.display = 'block';
}
the html
<div class="ajax-div">
<div class="searchbar">
<input type="text" onKeyUp="getScriptPage('box','text_content')" id="text_content">
</div>
<div id="box"></div>
</div>
I'm not sure what you are trying to do, but it seems you want something like this:
1- Change the way you display your rows so that the ID gets sent to your function as well:
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\"
onClick=\"display('".$row['CARD_NAME']."', " . $row['CARD_ID'] . ");\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
^^^^^^^^^^^^^^^^^^^^^^^^^
2- Change your display function to redirect
function display(word, id)
{
// document.getElementById('text_content').value = word;
// document.getElementById('box').style.display = 'none';
// document.getElementById('text_content').focus();
window.location.href = "some_page.php?card_id=" + id;
}
I have commented out the original lines because there doesn't seem much point in doing stuff on a page you are leaving anyway. You could also completely remove the word parameter if this is the solution you are looking for.

Categories