Javascript: Ajax problems after watching Bucky's tutorial - javascript

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

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

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

JavaScript xmlhttp read from feed

I'm trying to use javascript and read from http://search.yahooapis.com/ WebSearchService /V1/webSearch?appid=YahooDemo &query=persimmon&results=2 using xmlhttp. I'm getting an error because it cannot read
<script type="text/javascript">
url="http://search.yahooapis.com/ WebSearchService /V1/webSearch?appid=YahooDemo &query=persimmon&results=2";
var xmlhttp = null;
if (window.XMLHttpRequest)
{
xmlhttp = new XMLHttpRequest();
if ( typeof xmlhttp.overrideMimeType != 'undefined')
{
xmlhttp.overrideMimeType('text/xml');
}
}
else if (window.ActiveXObject)
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert('Perhaps your browser does not support xmlhttprequests?');
}
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
alert("success");
}
else
{
alert("failure");
}
};
</script>
Unless your web site is hosted on search.yahooapis.com you're probably encountering the Same Origin Policy.
This is causing your outgoing request to return with a 404 status code:
You should be using JSONP instead of XMLHttpRequest:
<!DOCTYPE html>
<html>
<head>
<title>JavaScript file download</title>
<script type="text/javascript">
function yahooApi(resp) {
var scriptEl = document.getElementById("yahooApiJsonP");
scriptEl.parentNode.removeChild(scriptEl);
console.log(resp);
}
window.onload = function() {
var scriptEl = document.createElement("script");
scriptEl.id = "yahooApiJsonP";
scriptEl.src = "http://search.yahooapis.com/WebSearchService/V1/webSearch?output=json&callback=yahooApi&appid=YahooDemo&query=persimmon&results=2";
document.body.appendChild(scriptEl);
};
</script>
</head>
<body>
<p>This is a test</p>
</body>
</html>
This will send the request, which will return a 200 OK status:
It also looks like this service has been shut down:

Categories

Resources