new to ajax, Object not found, - javascript

Hey guys I'm trying to work with AJAX for my first time using Javascript, PHP, and HTML. I have created the following code, and saved it in the htdocs folder in xampp. xampp is up and running but every time I navigate to localhost/foodstore.html nothing works I just get the error "Object not found!" I've Checked my code over a few times with a tutorial Im following, and found and corrected quite a few errors. I was wondering if the Object not found is because of my code or something else I am doing wrong. This is also my first time really using PHP and xampp. Also is there any other method that you would recommend to learn AJAX?
HTML
<html>
<head>
<script type= "text/javascript" src="foodStore.js"></script>
</head>
<body onload="process()">
<h3>Quaff Bucket</h3>
Enter the food you are looking for:
<input type="text" id="userInput"/>
<div id="underInput"/>
</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('bacon','beans','chicken');
if(in_array($food,$foodArray)){
echo 'we do have'.$food.'!';
}
elseif($food==''){
echo 'Please Enter a food you idiot!';
}
else{
echo 'we do not have'.$food.'punk!';
}
echo'</response>';
?>
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 the object");
}
else{
return xmlHttp;
}
}
function process(){
//states 4 and 0 mean that the object is free for communication
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
//get the info from the web page
food = encodeURICompnent(document.getElementById("userInput").value);
// (Request type,where it is sending,should it be handled asynchronously)
xmlHttp.open("GET","foodstore.php?food="+food,true);
xmlHttp.onreadystatechange =handleServerResponse;
xmlHttp.send(null);
}
else{
//wait 1 second before trying again
setTimeout('process()',1000);
}
}
function handleServerResponse(){
//4= done communicating
if(xmlHttp.readyState==4){
//200= Object is ok
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
//response is the only child in the xml page data= the response that would be genterated from the PHP
message = xmlDocumentElement.firstChild.data;
//makes underInput= to message
document.getElementById("underInput").innerHTML='<span style ="color:blue">'+message +'</span>';
setTimeout('process()',1000);
}else{
alert('something went wrong');
}
}
}

Related

Ajax with javascript not working on wamp server

I am new to ajax and was following a youtube tutorial to create a simple food search app
where users enter food name in input field it shows the name below else it
says that food not available
but somehow its not working on wamp server ..it shows the error alert instead
here is my code
index.html
<!Doctype html>
<html lang = "en">
<head>
<title>Ajax app</title>
<meta charset = "UTF-8">
<style>
</style>
<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"></div>
</body>
</html>
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("can't create that object boss");
}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()
{
//readystate 4 whenever response is ready and object done communicating
if(xmlHttp.readyState==4){
//state 200 means communiaction went ok
if(xmlHttp.readyState==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 please.";
}
else
{
echo"sorry but we don't even sell" . $food. "!";
}
echo "</response>";
?>
any help will be highly appreciated ,thanks
Please do NOT use xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");. Your best bet is to combine jQuery, but "ActiveXObject("Microsoft.XMLHTTP")" is obsolete (even for Microsoft environments), and unsupported on many browsers.
Here's a simple example (no jQuery):
var xmlhttp = new XMLHttpRequest();
var url = "myTutorials.txt";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myArr = JSON.parse(this.responseText);
console.log('myArr', myArr);
}
};
xmlhttp.open("GET", url, true);
This syntax is supported on ALL contemporary browsers ... and has been supported by Microsoft since IE7 (since 2006).
ALSO:
You definitely want to learn about Chrome Developer Tools (part of the Chrome browser), if you're not already familiar with it:
https://developers.google.com/web/tools/chrome-devtools

How do I use AJAX to communicate with and run code on a server?

I've been learning to use AJAX with the GET request that allows me to access a PHP script with an array of data on a server. I want to be able to send a request that tells the server to run code that will open an application and manipulate some info on this application.
Here is the code I use to firstly communicate with the server, then send a request to the server and finally handle responses from the server.
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) //State were object is free and ready to communicate with server
{
food = 'bacon';
xmlHttp.open("GET", "ExecuteMaya.php?food="+food,true); //Creates request that we are sending to server
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200) //Means communication was successful
{
var xmlResponse = xmlHttp.responseText;
var xmldom = (new DOMParser()).parseFromString(xmlResponse, 'text/xml');
var text = xmldom.getElementsByTagName("response")[0];
var message = text.childNodes[0].nodeValue;
foodTextOutput = message;
setTimeout('process()', 1000);
}
else
{
alert('Something went wrong!');
}
}
}
Here is the PHP I was using while I was learning how to use AJAX. I got the following error when I printed the 'xmldom' variable from the above code to the console and inspected it - "error on line 2 at column 1: Extra content at the end of the document". This may be a different question to my original post, but I thought I'd bring up that this error occurred. This then had a knock on effect for the line 'var message = text.childNodes[0].nodeValue;' which produced the error - "Uncaught TypeError: Cannot read property 'childNodes' of undefined".
<?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 idiot';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
The code that I have been working with to learn AJAX may not be relevant, I just thought I'd post it in case I can use some of this code that has already been written.
To sum up, I want to be able to do be able to send a boolean, or whatever is viable with AJAX, to the server that tells it to run a script. This script will then open a Maya application and run some Python code that I have written.
Thank you in advance!
As soon as you call the PHP file, this begins running code on the server. If you want to run an external application from PHP, take a look at the exec() function:
http://php.net/manual/en/function.exec.php
You have jQuery listed in your question tags. Have you compared the javascript and jQuery code?
The advantages of using jQuery are:
less typing,
simpler structure
automatically cross-browser
easily use Promises interface
Have a look at these examples and see if you prefer the jQuery AJAX methodologies:
Three simple examples
dynamic drop down box?
Chain AJAX Requests with jQuery Deferred

Javascript: Ajax problems after watching Bucky's tutorial

I watched Bucky's tutorial before and I cannot get this to work the error being shown is
index.php:62 Uncaught TypeError: Cannot read property 'documentElement' of undefinedhandleServerResponse # index.php:62
The JS is in the index.php here is the index.php
index.php
<!DOCTYPE html>
<html lang="en-US">
<head>
<script src="jquery.js"></script>
<script type="text/javascript">
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if (window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(error)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(error)
{
xmlHttp = false;
}
}
if (!xmlHttp)
{
alert("XMLHttpRequest failed");
}
else
{
return xmlHttp;
}
}
function process()
{
if (xmlHttp.readyState === 0 || xmlHttp.readyState === 4)
{
var food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET", "ajax_content.php?food" + food, true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send();
}
else
{
setTimeout("process()", 1000);
}
}
function handleServerResponse()
{
if (xmlHttp.readyState === 4) //done loading
{
if (xmlHttp.status === 200)
{
var xmlResponse = xmlHttp.reponseXML;
var xmlDocumentElement = xmlResponse.documentElement;
var message = xmlDocumentElement.firstChild.data;
document.getElementById("userInput").innerHTML = message;
setTimeout("process()", 1000);
}
else
{
alert("Error loading content");
}
}
}
</script>
</head>
<body onload="process()">
<input type="text" id="userInput" />
<div id="userInput">
</div>
</body>
</html>
And now ajax_content.php
ajax_content.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");
if (in_array($food, $foodArray))
{
echo 'We do have '.$food.'';
}
else if ($food == '')
{
echo 'Please enter a food'.$food.'';
}
else
{
echo 'We do not have '.$food.'';
}
echo '</response>';
?>
I read someones similar post but his was mainly syntax errors, why is this not working? What can I do to fix this?
believing this doc, and particularly this quote:
The XMLHttpRequest.responseXML property returns a Document containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or if the response cannot be parsed as XML or HTML. The response is parsed as if it were a text/xml stream. When the responseType is set to "document" and the request has been made asynchronously, the response is parsed as a text/html stream.
and given you are receiving a 200 from the server, it probably means that your server didn't send you back valid xml.
You should inspect the response data using the network panel of you dev tools (press F12 in your browser).

First steps wiht AJAX - can't find mistakes

I'm doing my first steps with AJAX and PHP, following a book ("AJAX & PHP: Building Responsive Web Aplicattions"). I tried to do something similar to one of the first exercises on my own. The first time I runned the code it didn't work. I checked it out and I didn't find any mistakes. Then I compared both codes line by line, and they looked exactly the same to me. I couldn't find any difference. The problem is the first code works; the divMessage changes its content at the same time you're writting in the input, but this doesn't happen with my code, and I really can't figure out why, because both codes are practically the same to me.
Original Code (HTML):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="quickstart.js" language="Javascript"></script>
</head>
<body onload='process()'>
Server wants to know your name:
<input type="text" id="myName"></input>
<div id="divMessage"></div>
</body>
</html>
My code (HTML):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script language="Javascript" type="text/javascript" src="test.js"></script>
</head>
<body onload='process()'>
Ingress a number:
<input type="text" id="number"></input>
<div id="textbox"></div>
</body>
</html>
=====================
Original Code(JS):=====================
// stores the reference to the XMLHttp object
var xmlHttp = createXMLHttpRequest();
// retrieves the XMLHttpRequest object
function createXMLHttpRequest(){
// will store the reference to the XMLHttp object
var xmlHttp;
// if running IE
if (window.ActiveXObject){
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e) {
xmlHttp = false;
}
}
// if running Mozilla or other browsers
else {
try {
xmlHttp = new XMLHttpRequest();
}
catch(e) {
xmlHttp = false;
}
}
// return the object created or display an error message
if(!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
// make asynchronus HTTP request using XMLHttpRequest object
function process(){
// proceed only if the XMLHttpRequest object isn't busy
if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0){
// retrieves the name typed by the user on the form
// La función encodeURIComponent() reemplaza todos los caracteres
// que no se pueden utilizar de forma directa en las URL por su representación hexadecimal.
name = encodeURIComponent(document.getElementById("myName").value);
// execute the quickstart.php page from the server
xmlHttp.open("GET", "quickstart.php?name=" + name, true);
// define the method to handle server responses
// the function is be called automatically when the state of the request changes
xmlHttp.onreadystatechange = handleServerResponse;
// make the server rqeuest
xmlHttp.send(null);
}
else{
// if the connection is busy, try again after one second
setTimeout('process()', 1000);
}
}
// executed automatically when a message is received from the server
function handleServerResponse(){
// move forward only if the transaction has completed
if (xmlHttp.readyState == 4){
// status of 200 indicates the transaction has completed successfully
if (xmlHttp.status == 200){
// extract the XML retrieved from the server
xmlResponse = xmlHttp.responseXML;
//obtain the document element (the root element) of the XML structure
xmlDocumentElement = xmlResponse.documentElement;
// get the text message, wich is in the first child
// of the document element
helloMessage = xmlDocumentElement.firstChild.data;
// update the client display using the data received from the server
document.getElementById("divMessage").innerHTML = helloMessage;
// restart sequence
setTimeout('process()',1000);
}
// a HTTP status different than 200 signal error
else {
alert ("There was a problem accessing the server: " + xmlHttp.statusText);
}
}
}
My Code (JS):
var xmlHttp = createXMLHttpRequest();
function createXMLHttpRequest(){
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 ("El objeto XMLHttpRequest no pudo ser creado.");
}
else {
return xmlHttp;
}
}
function process(){
if (xmlHttp.readyState == 4 || xmlHttp == 0){
number = encodeURIComponent(document.getElementById("number").value);
xmlHttp.open("GET", "test.php?number=" + number, 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;
helloMessage = xmlDocumentElement.firstChild.data;
document.getElementById("textbox").innerHTML = helloMessage;
setTimeout("process()",1000);
}
else {
alert ("Hubo un problema al acceder al servidor: " + xmlHttp.statusText);
}
}
}
=====================
Original Code(PHP):=====================
<?php
// generate the XML output
header('Content-Type: text/xml');
// generate the XML header
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
// create the <response> element
echo '<response>';
// retrieve the user name
$name = $_GET['name'];
// generate output depending of the user name received from client
$usernames = array('PABLO','JOSE','JUAN','CARLOS','YODA');
if (in_array(strtoupper($name), $usernames))
echo 'Hello ' . htmlentities($name);
else if (trim($name) == '')
echo 'Stranger, please tell me your name.';
else
echo htmlentities($name) . ', I don\'t know you.';
// close the <response> element
echo '</response>';
?>
My Code (PHP):
<?php
header ('Content-type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$number = $_GET['number']
echo 'El número ingresado es: ' . htmlentities($number);
echo '</response>';
?>

JavaScript/AJAX is saying "undefined" when it should show a picture

On my register page, I am trying to set it up so that when somebody enters a username into the username box, it will either show a green check mark if the username doesn't exist, or a red 'X' if the username already exists. When the page loads though (the body tag is <body on_load="process();">), it doesn't come up with a picture, it comes up with the word "undefined".
JavaScript code:
var xmlHttp = createXmlHttpRequestObject();
//Create object for function
function createXmlHttpRequestObject(){
var xmlHttp;
//Check if IE
if(window.ActiveXObject){
try{
//Setting variable equal to object for IE
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
//Can't set variable equal to something
xmlHttp = false;
}
}else{
//Anything not IE
try{
//Want to use this object if not IE
xmlHttp = new XMLHttpRequest;
}catch(e){
//Can't set variable equal to something
xmlHttp = false;
}
}
//If couldn't set object
if(!xmlHttp){
//Tell people that JS couldn't create the object (new XMLHttpRequest or ActiveXObject)
alert("Couldn't create an object with JavaScript!");
}else{
//Return object
return xmlHttp;
}
}
//Use this attribute for body tag: <body onload="process()">
function process(){
/*readyState:
0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready
*/
try{
//Check if ready to communicate
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
//<input type="text" id="userInput" /> relates to this
//Set variable to value they typed in
username = encodeURIComponent(document.getElementById("register_name").value);
//Creates request to send to server
//Need PHP file, GET would be in PHP file, also can be POST, etc.
xmlHttp.open("POST","functions/check_used.php",true);
//Doing something to make it pretend like it's a form, for POST
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//Handle server response when server responds to the request
xmlHttp.onreadystatechange = handleServerResponse;
//Send request (this is used for POST, use null when using GET)
xmlHttp.send("username="+username);
}else{
//Not ready to communicate, wait for 1 second and try again
setTimeout('process()',1000);
}
}catch(e){
//Something doesn't work, tell them what happened
alert(e.toString());
}
}
//When response received, tells what to do with it
function handleServerResponse(){
//Response done communicating
if(xmlHttp.readyState==4){
//Communication went OK
if(xmlHttp.status==200){
//Put response into variable
xmlResponse = xmlHttp.responseXML;
//Get document element
xmlDocumentElement = xmlResponse.documentElement;
//Get data from XML file
message = xmlDocumentElement.firstChild.data;
//Access document, put it in element on page, innerHTML is stuff shown on webpage
document.getElementById("checkedUser").innerHTML = message;
//Pause 1 second before communicating with server again
setTimeout('process()',1000);
}else{
//There was an error with data
alert('Something went wrong!');
}
}
}
On the register page, I have an input box with the div next to it:
<input type="text" id="register_name" name="username" /><div id="checkedUser"></div>
Finally, I have the PHP file that it is posting to:
<?php
require_once('../includes/db.php');
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<username>';
$check_username = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username");
$check_username->bindValue(":username",$_POST['username'],PDO::PARAM_STR);
$check_username->execute();
$check_username = $check_username->fetch();
if($check_username[0] == 0){
echo '<img src="images/success.png" />';
}else{
echo '<img src="images/error.png" />';
}
echo '</username>';
?>
I have tried troubleshooting it, but I couldn't figure out what was wrong.
Listen for keystrokes in input, and check username when the input changes :
$(function() {
$('#register_name').keyup(function() {
$.ajax({
type: 'POST',
url : 'functions/check_used.php',
data: {username : this.value},
success: function(result) {
$('#checkedUser').html(result);
}
});
});
});
And there's no need to return XML:
<?php
require_once('../includes/db.php');
header('Content-Type: text/html');
$check_username = $db->prepare("SELECT COUNT(*) FROM `users` WHERE `username` = :username");
$check_username->bindValue(":username",$_POST['username'],PDO::PARAM_STR);
$check_username->execute();
$check_username = $check_username->fetch();
if($check_username[0] == 0){
echo '<img src="images/success.png" />';
}else{
echo '<img src="images/error.png" />';
}
?>
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
should be
if(xmlHttp.readyState== 4 && xmlHttp.status == 200){

Categories

Resources