I'm learning AJAX and XML this days. Recently I have ran into a stupid problem.
I try to build a simple program that will show me in a <div> all that I input into an input box.
For some reason when I try to use the .responseXML property my program won't run. Note that when I use the .responseText everything works fine.
my html code :
<!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>Untitled Document</title>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<h3> the chuff bucket </h3>
<body onload="process()">
<input type="text" id="userInput"/>
<div id="underInput"></div>
</body>
</html>
my php code:
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>';
echo '<response>';
$food=$_GET['food'];
echo $food;
echo '</response>';
?>
my js code:
// JavaScript Document
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 object");
}else{
return xmlHttp;
}
}
function process(){
var x = xmlHttp.readyState
if(xmlHttp.readyState==0||xmlHttp.readyState==4){
food = encodeURIComponent(document.getElementById("userInput").value)
xmlHttp.open("GET","foodstore.php?food=" + food , true);
x=xmlHttp.readyState;
xmlHttp.onreadystatechange= handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
var xmlResponse= xmlHttp.responseXML;
root = xmlResponse.documentElement;
alert(root.firstchild);
//message= root.firstChild.data;
document.getElementById("underInput").innerHTML= '<span style="color:blue">' + xmlResponse + '</span>';
setTimeout('process()', 1000);
}else{
alert('not working');
}
}
}
Thanks to the helpers.
Did you tried with jQuery ? It may be easier to do. You can specify the data type
function ajaxJQueryRequest(url,afterReqFunction){
var request = $.ajax({
url: url,
type: "GET",
crossDomain: true,
dataType: "xml"
});
request.done(function(msg) {
afterReqFunction(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
}
Ok I think I found the bug.
I entered the url of the php file (that sending the response to the html) and got the following error:
"This page contains the following errors:
error on line 2 at column 6: XML declaration allowed only at the start of the document"
after I deleted the blank space at the top of my php I received a new error, after I fixed the new error everything worked like a charm... thanks a lot!!
Related
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
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).
I feel like I'm probably about 90% of the way there, and just need some help with that last 10%. I've looked at a number of different examples, and tried to piece together a solution, but haven't figured it out, so I'm looking for some guidance.
I have a small html page, with a little javascript, and a short .php that is adding the received data to a database.
I can see that the code is getting into the ajax function, and then into the insert function. But it's not actually doing the insert. I suspect that it's never sending the data off to the php file, but I don't know that for sure.
Here's the html code:
<html>
<head>
<script type ="text/javascript" language="javascript">
function ajaxFunction(){
var ajaxRequest;
alert("enter ajax"); //just a testing line
try{
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('responseDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
alert("enter insert"); //just for testing
var type = $('#type').val();
var vintner = $('#vintner').val();
var myData = {"type": type, "vintner": vintner,};
$.ajax({
url: "bottleAdd.php",
type: "POST",
data: "myData",
success: function(data, status, xhr)
{
$("$bottleAdd").html(data);
$("type").val();
$("vintner").val();
}
});
}
</script>
<title>Simple Add</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="addBottle">
<table>
<tr>
<td>Type: <input type="text" id="type" /></td>
<td>Vintner: <input type="text" id="vintner" /></td>
</tr>
<tr>
<td><button onClick="ajaxFunction()">Save Bottle Now</button></td>
</tr>
</table>
</div>
<div id="responseDiv">Response will appear here</div>
</body>
</html>
And here's the php
<?php
require_once 'login.php';
$conn = mysqli_connect($db_hostname, $db_username, $db_password, $db_database) or die("Connection failed: " . mysqli_connect_error());
$wineType = $_POST['type'];
$vintner = $_POST['vintner'];
$sql = "INSERT INTO bottleSimple (winetype, vintner)"
. " values ('$wineType', '$vintner')";
if (mysqli_query($conn, $sql)) {
echo "Successfully Inserted";
} else {
echo "Insertion Failed<br />";
echo $sql;
}
?>
I know there are some things to do in the php (prevent sql injection for example). But right now, I'm less concerned about that, and more about just figuring out how to get this to run correctly.
Any help would be appreciated.
Thank you.
You mixed plain JS AJAX with jQuery's ajax wrapper.
Change your code to the following:
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<title>Simple Add</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type ="text/javascript" language="javascript">
var type = $('#type').val();
var vintner = $('#vintner').val();
var myData = {"type": type, "vintner": vintner};
$.ajax({
url: "bottleAdd.php",
type: "POST",
data: myData,
success: function(data) {
$("#responseDiv").html(data);
}
});
</script>
</head>
The rest is without a change.
That way you will use jQuery AJAX.
By the way, it is a good practice to place meta tags a the beginning of your head tag, because tag like the charset will cause the browser to start reading your page again from the beginning.
You mixed two invoke methods of XHR - the native method and jQuery method.
If You go for native method with creating native xhr objct, You should operate only with the ajaxRequest variable which keeps the native XHR object. The solution is remove the code staring with
$.ajax
and, after define the onstatechange event, add Your request params, and finnaly send your xhr. So:
function ajaxFunction() {
var ajaxRequest;
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState === 4) {
var data = ajaxRequest.responseText;
console.log(data);
// do something with response data...
}
}
var type = 'atype';
var vintner = 'avintner';
var formData = new FormData();
formData.append("type", type);
formData.append("vintner", vintner);
ajaxRequest.open('POST', 'bottleAdd.php', true);
ajaxRequest.send(formData);
}
should work.
Try this: you may wrong use this code "mydata" it change to mydata..
for see result look in console.
function ajaxFunction() {
var ajaxRequest;
alert("enter ajax"); //just a testing line
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser broke!");
return false;
}
}
}
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
var ajaxDisplay = document.getElementById('responseDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
alert("enter insert"); //just for testing
var type = $('#type').val();
var vintner = $('#vintner').val();
var myData = {
"type": type,
"vintner": vintner,
};
$.ajax({
url: "http://stackoverflow.com/index.php",
type: "POST",
data: myData,
success: function(data, status, xhr) {
$("$bottleAdd").html(data);
$("type").val();
$("vintner").val();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<head>
<title>Simple Add</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<div id="addBottle">
<table>
<tr>
<td>Type:
<input type="text" id="type" />
</td>
<td>Vintner:
<input type="text" id="vintner" />
</td>
</tr>
<tr>
<td>
<button onClick="ajaxFunction()">Save Bottle Now</button>
</td>
</tr>
</table>
</div>
<div id="responseDiv">Response will appear here</div>
</body>
</html>
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');
}
}
}
books.xml:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<datas>
<book>
<id>
1
</id>
<title>
PHP Enterprise
</title>
<author>
Wiwit
</author>
</book>
<book>
<id>
2
</id>
<title>
PHP Undercover
</title>
<author>
Wiwit
</author>
</book>
</datas>
test.php:
<!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>Ajax Client</title>
<script type="text/javascript">
var xmlHttp = createXmlHttpRequestObject();
// creates XMLHttpRequest Instance
function createXmlHttpRequestObject(){
// will store XMLHttpRequest object
// at here
var xmlHttp;
// works all exceprt IE6 and older
try
{
// try to create XMLHttpRequest object
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
// assume IE 6 or older
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){ }
}
// return object or display error
if (!xmlHttp)
alert("Error creating the XMLHttpRequest Object");
else
return xmlHttp;
}
function process()
{
if(xmlHttp)
{
try
{
xmlHttp.open("Get","books.xml", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
catch(e)
{
alert("Can't connect to server\n" + e.toString());
}
}
}
function handleRequestStateChange()
{
myDiv = document.getElementById("myDivElement");
if(xmlHttp.readyState == 1)
{
myDiv.innerHTML += "Request status: 1 (loading) <br/>";
}
else if (xmlHttp.readyState == 2)
{
myDiv.innerHTML += "Request status: 2 (loaded) <br/>";
}
else if (xmlHttp.readyState == 3)
{
myDiv.innerHTML += "Request status: 3 (interactive) <br/>";
}
else if (xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
try
{
handleXMLData();
}
catch(e)
{
alert("Error reading the response: " + e.toString());
}
}
else
{
alert("Problem retrieving data:\n" + xmlHttp.statusText);
}
}
}
function handleXMLData()
{
var xmlResponse = xmlHttp.responseXML;
xmlRoot = xmlResponse.documentElement;
idArray = xmlRoot.getElementsByTagName("id");
titleArray = xmlRoot.getElementsByTagName("title");
authorArray = xmlRoot.getElementsByTagName("author");
var html = "";
for( var i=0; i<titleArray.length; i++)
{
html += idArray.item(i).firstChild.data + ", " + titleArray.item(i).firstChild.data + ", " + authorArray.item(i).firstChild.data + "<br/>";
}
myDiv = document.getElementById("myDivElement");
myDiv.innerHTML += "Server says: <br/>" + html;
}
console.log(xmlRoot);
</script>
</head>
<body onload="process()">
Our collections:
<div id="myDivElement" />
</body>
</html>
Above code is taken from: http://www.phpeveryday.com/articles/AJAX-Client-Side-Processing-XML-Data-use-XMLHttpRequest-P356.html
In this function function handleXMLData(), some places use var such as var xmlResponse = xmlHttp.responseXML;, some places did not use var, such as: xmlRoot = xmlResponse.documentElement; so my question is:
why not put var in front of xmlRoot?
usually inside function(){}, if we do not put var in front of variable, it will be global variable, such as:
function test()
{ gar = '9';}
test();
console.log(gar);
But when I put console.log(xmlRoot); just before tag </script>, in chrome console, it shows:Uncaught ReferenceError: xmlRoot is not defined, why? Is not xmlRoot a global variable since there is no var in front of it?
var may not have used here because the author wants the variable to be a global one
It is throwing the error because when console.log(xmlRoot);, the execution context is unaware about xmlRoot since handleXMLData may not have executed yet (because it a used in the callback function to an asynchronous call)
xmlRoot will be a global variable if it has been defined. If the function that refers to it has not been called, xmlRoot won't be defined.
You tested xmlRoot just before the script exits, i.e. during the first execution of the code, before handleXMLData() had been called.