Ajax with javascript not working on wamp server - javascript

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

Related

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

My AJAX script is not giving any output

index.php:-
<!DOCTYPE html>
<html>
<head>
<script src="food.js"></script>
<link rel="stylesheet" type="text/css" href="css/bootstrap.min.css">
</head>
<body onloadd="process()">
<div class="container">
<h2 class="page-header">The Chuff Bucket</h2>
<strong>Enter the food you want to order:</strong><br><br>
<input type="text" class="form-control" id="userInput">
<div id="underInput">
</div>
</div>
</body>
</html>
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','loaf','sandwich','pizza');
if(in_array($food, $foodArray))
{
echo 'We do have'.$food.'!';
}
elseif($food=='')
{
echo 'Enter a food chomu';
}
else
{
echo 'We have no'.$food;
}
echo '</response>';
?>
food.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("Cannot create the object!!");
}
else
{
return xmlHttp;
}
}
function process() {
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
{
var 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;
xmlDocElm = xmlResponse.documentElement;
msg = xmlDocElm.firstChild.data;
document.getElementById("underInput").innerHtml = '<span style="color:blue;">'+msg+'</span>';
setTimeout('process()',1000);
}
else
{
alert("Something is wrong!!");
}
}
}
I just started with AJAX and this is my first code. I have even free hosted it. Here is the url:- Chuff Bucket
I have no idea what is wrong with the code. I have done the same as shown in the tutorial.
This isn't doing what you think:
xmlHttp.onreadystatechange = handleServerResponse();
This is invoking the handleServerResponse function immediately (which doesn't do anything, because xmlHttp.readyState isn't 4 at that time), and setting the result of that function to the onreadystatechange callback. Since that function doesn't return anything, that result is undefined.
Don't invoke the function, just set it like a variable as the callback:
mlHttp.onreadystatechange = handleServerResponse;
There is javascript framework offering a simplified way to use Ajax request like jQuery Ajax.
Using this kind of framework is a good way to simplify your code and to not repeat yourself DRY.
A jQuery version :
<script>
$(document).on('keyup', '#userInput', function(){
var food = $(this).val(); // # <= means ID
$.get('foodstore.php', 'food='+food, function(response){
$('#underInput').html(response);
});
});
</script>

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>';
?>

new to ajax, Object not found,

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

XML using Javascript in Google Chrome

Hy all,
I am using a code that goes through an XML file and show me the data..
That code works great in IE, Firefox and Opera..
Now I would like to know how to configure it to work on Chrome..
Using the navigator.appName == "Microsoft Internet Explorer" and navigator.appName == "Netscape", I was capable of testing the identity of the browser used, and whether to use ActiveX objects or httpRequest.
Keeping in mind, when alerting the navigator.appName , on Chrome, Firefox and Opera, I get Netscape.
This is the full version of my code:
<html>
<body>
<script type="text/javascript">
alert(navigator.appName);
if (navigator.appName == "Microsoft Internet Explorer") {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
xhttp.open("GET", "http://www.multimediaprof.com/test/emp2.xml", false);
}
else if (navigator.appName == "Netscape") {
xhttp = new XMLHttpRequest();
alert("step 1");
xhttp.open("GET", "emp2.xml", false);
}
alert("step 2");
xhttp.send("");
alert("step 3");
xmlDoc = xhttp.responseXML;
alert("step 4");
alert(xmlDoc);
document.write(xmlDoc.documentElement.nodeName + " loaded");
alert("step 5");
var str = xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
alert("step 6");
alert(str);​
</script>
</body>
</html>
New full version of code suggested now :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var xhttp, xmlDoc, str;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
xhttp.open("GET", "emp2.xml", false);
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
xhttp.open("GET", "http://www.multimediaprof.com/test/emp2.xml", false);
} else {
alert("Cannot create XmlHttpRequest object");
}
if (xhttp) {
xhttp.send("");
if (xhttp.responseXML != null) {
xmlDoc = xhttp.responseXML;
str = xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
alert(str);
} else {
alert("Server response was invalid.");
}
}
</script>
</head>
</html>
Just don't use appName at all.
var xhttp, xmlDoc, str;
if (window.XMLHttpRequest) {
xhttp = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhttp = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert("Cannot create XmlHttpRequest object");
}
if (xhttp) {
xhttp.open("GET", "emp2.xml", false);
xhttp.send();
if (xhttp.responseXML != null) {
xmlDoc = responseXML;
str = xmlDoc.getElementsByTagName("to")[0].childNodes[0].nodeValue;
alert(str);
} else {
alert("Server response was invalid.");
}
}
Note:
You must declare all the variables you use. There is no reason ever not to declare a variable.
You really should use asynchronous requests. Learn how to use them. Synchronous requests are bad and wrong.
You should never ever use document.write().
You should always check things before you use them. For example, you cannot simply use xhttp.responseXML without even checking that it exists.
The same goes for getElementsByTagName("to")[0].childNodes[0].nodeValue. This can fail at any time. If you never expect an error here, at least wrap it in a try/catch block and handle unexpected errors gracefully.
There is console.log(). That's a lot better than alert().

Categories

Resources