Cannot read property 'readyState' of undefined - php

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;
}
}

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);
};

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.

Changing include direction with javascript

I'm trying to change an include path with JavaScript. It need's to go from this
<?php include 'sections/welcome.php'; ?>
to this
<?php include 'sections/new_visitor.php'; ?>
to this
<?php include 'sections/nda.php'; ?>
and so on... do anybody know how to code this in JavaScript?
you can't change how PHP is coded via javascript. You can send variables to php via javascript and then PHP responds to those variables... it looks like you have a registration of sorts. If you're using standard HTTP requests, you could use javascript to append a $_GET variable to the action link. For Instance:
$('#form').attr('action', $('#form').attr('action') + '?page=welcome');
Then, upon clicking the link, PHP will have access to $_GET['page'], so in php you could:
switch($_GET['page'])) {
case 'welcome':
include 'section/welcome.html';
break;
case 'nda':
include 'section/nda.html';
break;
}
Look at the if(message ===1) statement below:) sorry for being such a noob :P
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("cat create that object hos");
}
function newuser(){
if(xmlHttp.readyState ===0 || xmlHttp.readyState ===4){
name = encodeURIComponent(document.getElementById('name').value);
company = encodeURIComponent(document.getElementById('company').value);
nationalities = encodeURIComponent(document.getElementById('nationality').value);
phonenumber = encodeURIComponent(document.getElementById('phonenumber').value);
queryString = "?name=" + name + "&?company=" + company + "&?nationalities=" + nationalities + "&?phonenumber=" + phonenumber + "&?URL= newuser";
xmlHttp.open("GET", "/php/database.php?" + queryString, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('newuser()', 1000);
}
}
function handleServwerResponse(){
if(xmlHttp.readyState ===4){
if(xmlHttp.status === 200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
if(message === 1){
//I want to call a function here, so i can change the include path
}else{
document.getElementBy("underInput").innerHTML = 'User already exist klick to sign in here <p style="color:blue" onclick=""></p>';
}
}
}
}
}

xmlDocumentElement is not defined

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);

How to place PHP function result in particular <div>? I am using AJAX

I have implemented a dynamic creation of a HTML table using AJAX.
Here's what I've created:
index.php
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="ContactController.js">
</script>
</head>
<body>
<div class="main-wrapper">
<div id="menu">
<a href="javascript:void(0)" onclick="getAllContacts()">
Go to contacts
</a>
</div>
<div id="main-content">
</div>
</div>
</body>
</html>
ContactsController.js
function getAllContacts() {
// Manage new XmlHttpObject creation
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert ("Your browser is out of date. Please upgrade.");
return;
}
var url = "getAllContacts.php";
// Workaround for page caching
url = url + "?sid=" + Math.round(Math.random() * 1000000000);
xmlHttp.open("POST", url, true);
// Manage XmlHttpObject state change
xmlHttp.onreadystatechange = stateChanged;
xmlHttp.send(null);
}
function stateChanged() {
// Check if the XmlHttp request is complete
if (xmlHttp.readyState == 4) {
// Set the XmlHttp response in the contacts div
document.getElementById("main-content").innerHTML = xmlHttp.responseText;
}
}
// Creates a new XmlHttpObject
function GetXmlHttpObject() {
var xmlHttp = null;
try {
// XmlHttpObject constructor for Chrome, Firefox, Opera, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {
// XmlHttpObject constructor for Internet Explorer > v6.0
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
// XmlHttpObject constructor for Internet Explorer > v5.5
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
getAllContacts.php
<?php
include 'connectToMySQL.php';
$command = "SELECT * FROM contact";
$result = mysql_query($command);
echo "<table id='contactsTable' border='1'>";
// Table headers
echo "<tr>
<th>Name</th>
</tr>";
// Print all contacts
while($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>
<a href='#'
onclick=\"getContact('" . $row['DisplayName'] . "')\">"
. $row['DisplayName'] .
"</a>
</td>";
echo "</tr>";
}
echo "</table>";
mysql_close();
?>
So, clicking on a Go to contacts link activates a getAllContacts javascript function. That function calls getAllContacts php function which retrieves the data from MySQL database and places it in the contactsTable table.
What I need is to tell the function to place that table in the main-content div located in the index.php page. How do I achieve this? Thanks.
ok, so going from your comment about wanting two different possible target divs, just define your onreadystatechanged event inline and use a local variable to refer to the div...
function getAllContacts() {
// Manage new XmlHttpObject creation
var xmlHttp = GetXmlHttpObject(); // MAKE THIS LOCAL INSTEAD OF GLOBAL!
if (xmlHttp == null) {
alert ("Your browser is out of date. Please upgrade.");
return;
}
var url = "getAllContacts.php";
// Workaround for page caching
url = url + "?sid=" + Math.round(Math.random() * 1000000000);
xmlHttp.open("POST", url, true);
var targetDiv = document.getElementById(whateverIdYouWant);
// Manage XmlHttpObject state change
xmlHttp.onreadystatechange = function(){
// Check if the XmlHttp request is complete
if (xmlHttp.readyState == 4) {
// Set the XmlHttp response in the contacts div
targetDiv.innerHTML = xmlHttp.responseText;
}
}
xmlHttp.send(null);
}

Categories