First small foodstore-project with ajax - does not execute - javascript

I have just started to learn Ajax and have watched a tutorial on how to write a small input that checks whether a foodstore has something in stock or whether it hasn't.
I have double-checked the code several times but it still does not execute anything. I would be glad if anyone could help me here.
The code is basically three files:
Index.html
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The Food Store</h3>
<p>Enter the food you would like to have:</p>
<input type="text" id="userInput">
<div id="underInput"/>
</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', 'beef', 'ham');
if(in_array($food,$foodArray)) {
echo 'We do have '.$food'!';
echo '</response>';
}
}
?>
and finally the 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!");
else {
return xmlHttp;
}
}
// This is now the communication part!
function process() {
if(xmlHttp.readyState==0 || xmlHttp.readyState==4){
food = encodeURIComponent(document.getElmentById("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 styel="color:blue">' + message + '</span>';
setTimeout('process()',1000);
}else{
alter('Something went wrong!');
}
}
}
I would really appreciate some help. I also read in the youtube-comments that jQuery would rather be easier to use as far as the js part goes. Is that true?
Many thanks!

In the foodstore.js you have a litlle problem you have writed document.getElmentById("userInput").value and it must be
document.getElementById("userInput").value

Related

Resposexml returns null value

I am new to ajax. I wanted to create a simple webpage where it contains a button if clicked returns image dynamically.But the responseXML returns null value. Here is part of javascript code:
function process()
{
if(xmlhttp.readyState==4 || xmlhttp.readyState==0)
{
xmlhttp.open("GET","image.php",true);
xmlhttp.onreadystatechange = handleserverresponse;
xmlhttp.send();
}else{
setTimeout('process()',1000);
}
}
function handleserverresponse()
{
if(xmlhttp.readyState==4){
if(xmlhttp.status==200){
xmlResponse = xmlhttp.responseXML;
imag = xmlResponse.documentElement.firstChild.data;
document.getElementById("divimg").innerHTML=imag;
}
else{
alert("something went wrong");
}
}
here is php code:
<?php
header('Content-Type:text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo "<res>";
echo "<img src="a.jpg"/>";
echo "</res>";
?>
Your HTTP request is asynchronous. xmlhttp.responseXML won't have some value until xmlhttp.readyState has the value of 4.
var url = "http://localhost/xml.php?type=xml";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xmlhttp) {
xmlhttp.open("GET", url, true);
xmlhttp.setRequestHeader('Content-Type', 'text/xml');
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4) {
alert(xmlhttp.responseXML);
}
};
xmlhttp.send();
}
Additionaly, I don't think you need the setRequestHeader line. XML MIME type is required for response, not for request. Also, please respect good coding practices (don't forget var, DRY, etc.)
The reason responseXML was null because there is a mistake in PHP file.
I guess We cannot send HTML tags when content type is xml. Instead what we can do is echo source of image and modify JavaScript file to take that source and display using img tag.

Simple ajax script to display a book's name

I started learning Ajax and I did this simple HTML page that displays a user input, when he types the name of a book (stored in an array in the php file), using ajax, the user can see below the input the results while he types, this is the part I couldn't manage to do, Here's the code :
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="bookstore.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body onload="process()">
<h1>
Hadhemi's BookStore !
</h1>
Enter the book you want to order
<input type="text" id="userInput">
<div id="underInput"> </div>
</body>
</html>
And this is the JS file
// 3 functions : create an object, communicate and response
var xmlHttp=createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); //check for IE
}
catch (e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new XMLHttpRequest(); // ! IE
}
catch (e)
{
xmlHttp = false;
}
}
if (!xmlHttp)
alert("Can't Create that object");
else
return xmlHttp;
}
function process()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
book = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET","book.php?book=" + book,true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()',1000);
}
}
function handleServerResponse()
{
//sends back an xml file
if (xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement=xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML= message;
setTimeout('process()',1000);
}
else
{
alert("OOps! Something went wrong!");
}
}
}
And this is the PHP file :
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" enconding="UTF-8" standalone="yes" ?>';
echo'<response>';
$book = $_GET['book'];
$bookArray = array('Book1','Book2','Book3');
if(in_array($book, $bookArray))
echo 'We do have'.$book.'!';
elseif ($book='')
echo 'Enter a book name idiot!';
else
echo 'We dont have'.$book.'!';
echo'</response>';
?>
I can't manage to display what the JS file is supposed to do, anyone knows how to fix it?
EDIT: I placed all the files in the www folder under Wamp.
There are a few things wrong in what you posted.
Firstly, you have a typo in:
echo '<?xml version="1.0" enconding="UTF-8" standalone="yes" ?>';
^ the "n"
Which should read as encoding.
Having errors set to be displayed on your server would have thrown you the following:
XML Parsing Error: XML declaration not well-formed Location: http://www.example.com/book.php?book.php?book= Line Number 1, Column 21:
Plus, do keep in mind that, and as I stated in comments that Book1 and book1 are not treated the same, therefore the array keys are considered as case-sensitive.
Consult the following answer on Stack:
https://stackoverflow.com/a/5404753/
You're also doing an assignment for while using a single equal sign:
elseif ($book='')
^
rather than a comparison, which should contain an additional equal sign:
elseif ($book=='')
^^
References:
http://php.net/manual/en/language.operators.assignment.php
http://php.net/manual/en/language.operators.comparison.php
http://php.net/manual/en/function.error-reporting.php
Plus, make sure that PHP is indeed installed, running and properly configured.

XMLHttpRequest not working - no errors

I am trying to get this simple request working but I am not having much luck.
I have the "test.txt" file in the server folder as my html file containing the script provided below.
I viewed the file in Chrome, Firefox and IE11 with the same result. I can only see the "Initial text in the html page.." text from the html page. No errors and the text from my test.txt file is not getting displayed.
Could anyone please point me what the issue with my code is?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp:
}
function process(){
if(xmlHttp){
try{
xmlHttp.open("GET","test.txt", true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}
catch(e){
alert( e.toString() );
}
}
}
function handleServerResponse(){
output = document.getElementById('output');
if(xmlHttp.readyState==1){
output.innerHTML += "Status 1: server connection established <br />"
}
else if(xmlHttp.readyState==2){
output.innerHTML += "Status 2: request received <br />"
}
else if(xmlHttp.readyState==3){
output.innerHTML += "Status 3: server processing <br />"
}
else(xmlHttp.readyState==4){
if(xmlHttp.status=200){
try{
text = xmlHttp.responseText;
output.innerHTML += "Status 4: request is finished and response is ready<br />"
output.innerHTML += text;
}
catch(e){
alert( e.toString() );
}
}
else{
alert( xmlHttp.statusText );
}
}
}
</script>
</head>
<body onload="process()">
Initial text in the html page..<br>
<br>
<div id="output">
</div>
</body>
</html>
Ok, I figured it out....
it was one typo and one ommision
return xmlHttp: -> should be ; instead
and forgot "else"
else(xmlHttp.readyState==4){ -> should be else if (xmlHttp.readyState==4){

Plain Javascript (no JQuery) to load a php file into a div

Hi I don't know javascript but I am required to use it in one of my templates. I was googling around and found a solution whic is like this:
My Index.php file.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
window.onload = function(){
document.getElementById("aside").innerHTML="<img src='loadingImage.gif'>";
if(XMLHttpRequest) var x = new XMLHttpRequest();
else var x = new ActiveXObject("Microsoft.XMLHTTP");
x.open("GET", "other_content_1.php", true);
x.send("");
x.onreadystatechange = function(){
if(x.readyState == 4){
if(x.status==200) document.getElementById("aside").innerHTML = x.responseText;
else document.getElementById("aside").innerHTML = "Error loading document";
}
}
}
</script>
</head>
<body>
<div id="aside">This is aside</div>
</body>
</html>
My other_content_1.php file
<div id='other-content-1'>
<?php echo 'This text is loading via php command'; ?>
</div>
As this is the only Javascript function in my site I see no reason to load additional JQuery for it. I am sure there must be a way to do this with plain JavaScript / ajax without the need to load JQuery. Can anybody suggest the correct syntax to do so?
I want to happen asynchronously while the page continues to load.
from http://www.tutorialspoint.com/ajax/ , using plain XHR (XmlHttpRequest)
function loadPage() {
var ajaxRequest;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "ajax-example.php", true);
ajaxRequest.send(null);
}
loadPage();
Try this:
window.onload = function(){
aside = document.getElementById("aside");
aside.innerHTML="<img src='loadingImage.gif'>";
if(XMLHttpRequest) var x = new XMLHttpRequest();
else var x = new ActiveXObject("Microsoft.XMLHTTP");
x.open("GET", "other_content_1.php", true);
x.send();
x.onreadystatechange = function(){
if(x.readyState == 4){
if(x.status == 200) aside.innerHTML = x.responseText;
else aside.innerHTML = "Error loading document";
}
}
}
And it is cross browser compatible, you never need the extra 32KB just to make a simple function supported cross browser.

My Ajax javascript code isn't working

My Ajax javascript code isn't working...
Here is the code:
function getMessages() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("box").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "process.php");
xmlhttp.send();
}
I have my php script just doing a test saying: this is a test.
I can't figure out what I did wrong. Chrome javascript debugger says that I have an unxpected token "."
PHP Code:
<?php if (!$_COOKIE["name"]) {
echo "<form method='get' action = 'process.php'><input type = 'text' name = 'name'><input type = 'submit' value = 'Submit'></form>";
} else {
echo '
function getMessages(){var xmlhttp;
if(window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest (); }
else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4&&xmlhttp.status==200) { document.getElementById("box").innerHTML=xmlhttp.responseText; } }
xmlhttp.open("GET","process.php") ;
xmlhttp.send(); }
var is={ie:navigator.appName=="Microsoft InternetExplorer",java:navigator.javaEnabled(),ns:navigator.appName=="Netscape",ua:navigator.userAgent.toLowerCase(),version:parseFloat(navigator.appVersion.substr(21))||parseFloat(navigator.appVersion),win:navigator.platform=="Win32"
}
is.mac=is.ua.indexOf("mac")>=0;
if(is.ua.indexOf("opera")>=0){is.ie=is.ns=false;is.opera=true;}
if(is.ua.indexOf("agecko")>=0)
{is.ie=is.ns=false;is.gecko=true;
}';
echo "<textarea id=box rows=20 cols=20></textarea>
<form method='get' action = 'process.php'>
<input type = 'text' name = 'message'>
<input type = 'submit' value = 'Submit'>
</form>";
} ?>
xmlhttp.readyStat should be xmlhttp.readyState perhaps?
readyStat should be readyState for one. Rest seems okay.
xmlhttp.send() to xmlhttp.send(null) can prevent IE bugs too

Categories