Simple ajax script to display a book's name - javascript

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.

Related

Getting undefined array key when passing data with XMLHttpRequest

I'm trying to pass a long formatted text string to a php process to save to a file. I am use the POST method as the string can be quite long. It seems to run thro the process and gives back the message 'File saved' but with the error message 'Undefined Array Key "data"' on line 2 of the php code. The file does not get saved and no data is being sent across from the XMLHttpRequest in the previous function.
My code is:- This gets 'str' from the previous function and is formatted correctly.
function getGame(str){
//Sends data to the php process "saveGame.php".
var data = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send(data);
}
it then goes the the 'saveGame.php' where the problem occurs on line 2.
<?php
$outputString = $_POST["data"];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
fwrite($fp, $outputString);
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
$message = "File saved!";
}
fclose($fp);
echo $message;
?>
I think my code of the process is okay but there is a problem with passing the "data" variable and I not sure what it is.
I tested the file saving process. I put a dummy string as a value of 'outputString' and it saved it. When I went back and used the current code the file was overwritten and was blank, indicating it had saved a blank string. So it seems no data is been passed to saveTeams.php although the saving of the file works.
I have got a reproducible example below. If you use it with the saveTeams.php file and a file to attempt to save the data to it should display the error I get in an alert drop down.
<!DOCTYPE html>
<head>
<title>Test program</title>
<script language="javascript">
function formatOutput() {
// lots of formatting goes on here
var formattedText = "This is a test"; //test data
getGame(formattedText);
}
function getGame(str){
//Sends data to the php process "save Game".
var data = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send(data);
}
</script>
</head>
<body>
<table width="1000" align="center" border="0">
<br />
<tr>
<td width="500"align="center" colspan="3" <button onclick="formatOutput()"/>Click on me</td>
</tr>
</table>
</body>
</html>
Hope this okay. I'm a bit new to this.
You are missing a post key
try changing this line to
var data = 'data='+str;

How to load data from an XML file using php to show it in an html page with javascript

I'm doing an assigment for my programming class. I need to show a table with two columns (name and lastname) of a list of friends. This data is stored in a XML file like this:
<?xml version='1.0' standalone='yes'?>
<amigos>
<amigo>
<nombre>Alejandra</nombre>
<apellido>Ponce</apellido>
</amigo>
<amigo>
<nombre>Dalia</nombre>
<apellido>Gordon</apellido>
</amigo>
I retrieve this data with php, like this:
<table width="200" border="1">
<tr align="center">
<td>NOMBRE</td>
<td>APELLIDO</td>
</tr>
<?php
$amigos = simplexml_load_file('listaamigos.xml');
foreach ($amigos->amigo as $amigo) {
echo '<tr>';
echo '<td>',$amigo->nombre,'</td>';
echo '<td>',$amigo->apellido,'</td>';
echo '</tr>';
}
?>
I call this php file with a function written in javascript language. I'm using ajax for this homework. My javascript file is the one I'm showing below:
var xmlHttp;
function createXmlHttpRequestObject() {
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 connect to the host');
else
return xmlHttp;
}
function cargarAmigos(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function cargar(url)
{
if(url=='')
{
return;
}
xmlHttp=createXmlHttpRequestObject();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = procesarEventos;
xmlHttp.send(null);
}
function procesarEventos()
{
if(xmlHttp.readyState == 4)
{
document.getElementById("listaAmigos").innerHTML= xmlHttp.responseText;
}
}
I use this javascript file in a html file. I call the function cargar () in the button's onclick event, like this:
<body>
<div id="listaAmigos" >
Lista amigos
</div>
<button onclick="cargarAmigos('procedimiento.php');">Lista Amigos Ajax</button>
</body>
The problem is that the code is not working. I mean that the names are not displaying at all in the table. Actually the table does not appear.
I'm pretty sure that the error is not in the code because it was working last week and I haven't changed the code since then. But today I loaded the html page just for "fun" and it wasn't showing my list of friends.
So I decided to open another project with uses the same algorithm and this one is not working too. I've checked that all the files are in the same folder. I've checked my xammp server and it's apache and mysql services are on. I have no idea what "thing" I could have done to cause this problem.
Any help will be really appreciated.
It looks like you should escape the ' character in this line:
alert('Can't connect to the host');
i.e. rewrite it like
alert("Can't connect to the host");
You can see that there's an error even just by looking at the formatting on Stack Overflow :)
Please refer to this question for the details on why it's working like that: When to use double or single quotes in JavaScript?

Getting a null value to database when AJAX is used

I got this registration code which was working fine but I decided to add AJAX to make it more dynamic but when I run it, my PHP code was saving null value to database.
This is what I know so far: whenever a user writes information in signup page it goes to AJAX and the ajax pass it along to php and then php saves the info into database and it echo a message and then it goes to ajax and then it displays the message. All of this works the only problem is that my php code is saving null value no matter what i write in signup page.
and i think this is the code thats not working properly but i just dont know the other way
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "signip_parse.php?username="+username+"&password="+password;
the following is rest of my code. this is the page were user puts information and its saved as signup.php
<head>
<script src = "ajax.js"></script>
<div id="content">
</head>
<body>
<form action="signip_parse.php" method="post" id="registration_form">
<p>Name <input type="text" name="username" id = "username"/></p>
<p>Password <input type="password" name="password" id = "password"/></p>
<p><input type = "button" value="sign up" id="submit" onclick = "hello()"/>
<input type="button" value="Back" onclick="return back()"/></p>
</form>
<div id="ack"><p>1</p></div>
</div>
</body>
and this is the ajax code that I got it from w3school ajax example and i saved it as ajax.js
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlhttp;
}
var HTTP = loadXMLDoc();
function hello(){
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
var url = "signip_parse.php?username="+username+"&password="+password;
HTTP.onreadystatechange=function()
{
if (HTTP.readyState==4 && HTTP.status==200)
{
document.getElementById("ack").innerHTML=HTTP.responseText;
}
}
HTTP.open("POST", url ,true);
HTTP.send();
}
and last this is the signip_parse.php where i managed to spell signup wrong
<?php
include_once("connect.php");
$user = mysql_real_escape_string( $_POST["username"]);
$password = mysql_real_escape_string( md5 ($_POST["password"]));
$sql = "INSERT INTO users (username, password) VALUES ('$user','$password')";
if(mysql_query($sql)){
echo "You have been successfully registered";
}
else{
echo "Something went wrong try again";
}
?>
Any help would be great. thanks guys
and yes i know md5 is broken but this is just a demo and intend to used something else.
Since you're sending a request as post, its important to add this on your XMLHttpRequest object:
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
And just combine them inside, no need to separate some parts. It would look something like this:
<script type="text/javascript">
function hello() {
var xmlhttp = new XMLHttpRequest();
var username = encodeURIComponent(document.getElementById('username').value);
var password = encodeURIComponent(document.getElementById('password').value);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("ack").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST", 'signip_parse.php', true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("username="+username+"&password="+password);
}
</script>
Here's what it would look like
Obligatory Note:
Please, don't use mysql_* functions in new code. They are no longer maintained and are officially deprecated. See the red box? Learn about prepared statements instead, and use PDO or MySQLi - this article will help you decide which. If you choose PDO, here is a good tutorial.
Ref: https://stackoverflow.com/a/12860140/3859027
You should consider also (if you're using PHP 5.5 or greater) to use PHP's native password hashing and replace that md5() instead. If you're below v5.5 then you could use the its compatibility pack

change a php variable using POST

trying to change a php variable via js and echo back but its not working, been on it for days!!
I have a function handleServerResponse() called below, that alerts connection status, and getting the ok at status 200 so cant understand why my php variabe is not changing! driving me insane!
function process() // send the info to the server
{
if(xmlHttp)
{
try
{
xmlHttp.open("GET","myFile.php?phpvar="+jsvar,true);
xmlHttp.onreadystatechange = handleServerResponse; //alerts connection status = all ok
xmlHttp.send(null);
}
catch(e)
{
alert(e.toString());
}
}
}
// server side script
<?php
echo '<?xml version="1.0" encoding = "UTF-8" standalone = "yes" ?>';
$phpvar;
$phpvar = $_GET['phpvar'];
echo "new phpvar value = ".$phpvar;
?>
Any help at all would be greatly appreciated.
Cheers
The following code achieves the aim you've stated. Not sure what your problem is, since you've neglected to post a complete example.
phpVarTest.html
<!DOCTYPE html>
<html>
<head>
<script>
"use strict";
function byId(e){return document.getElementById(e);}
window.addEventListener('load', onDocLoaded, false);
function myAjaxGet(url, callback)
{
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function()
{
if (this.readyState==4 && this.status==200)
callback(this);
}
ajax.onerror = function()
{
console.log("AJAX request failed to: " + url);
}
ajax.open("GET", url, true);
ajax.send();
}
function onDocLoaded()
{
byId('testBtn').addEventListener('click', onTestBtnClicked, false);
}
function onTestBtnClicked(e)
{
var jsvar = 'some arbitrary text';
var url = 'phpVarTest.php?phpvar='+jsvar;
myAjaxGet(url, onAjaxDone);
}
function onAjaxDone(ajaxObj)
{
byId('outputDiv').innerText = ajaxObj.response;
}
</script>
<style>
</style>
</head>
<body>
<button id='testBtn'>Initiate ajax request</button>
<div id='outputDiv'></div>
</body>
</html>
phpVarTest.php
// server side script
<?php
echo '<?xml version="1.0" encoding = "UTF-8" standalone = "yes" ?>';
$phpvar;
$phpvar = $_GET['phpvar'];
echo "new phpvar value = ".$phpvar;
?>
output
// server side script
<?xml version="1.0" encoding = "UTF-8" standalone = "yes" ?>new phpvar value = some arbitrary text
Note: you should place the comment in the php file inside of the php tags - otherwise, you'll see it in the output, as shown above.

Reading a txt file from Server, writing it to website

Here's my problem.
1) I'm wanting to create a txt file (or possibly a html file) to hold a paragraph of information to be written onto a when a user clicks a word. It's part of a game I am working on.
If you go to www.w3schools.com and go to their "try it" editor they have...
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp = XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
p = document.createElement("p");
p.innerHTML=xmlhttp.responseText;
document.getElementById("story").appendChild(p);
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="story"><h2>Let AJAX <i onclick=loadXMLDoc()>change</i> this text</h2></div>
</body>
</html>
This is exactly what I want my program to do (not the actual words of course) but I'm running html with an external .js sheet. Should I store my ajax somewhere else? Or, should my .txt file look different than just a bunch of words in it? I'm completely confused.
The fun part will be once this actually starts working, I'm going to have to implement an "onclick" event with italics inside of the txt file.
If there is a better way to do this then appendChild(p.innerHTML("lfjhdfh")) and AJAX please let me know asap. I have a total of 11 weeks to get this thing working for a school project LOL.
Try this, it just appends the text to the HTML of the body element:
function getFileFromServer(url, doneCallback) {
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = handleStateChange();
xhr.open("GET", url, true);
xhr.send();
function handleStateChange() {
if (xhr.readyState === 4) {
doneCallback(xhr.status == 200 ? xhr.responseText : null);
}
}
}
function ajax() {
getFileFromServer("Test.txt", function (text) {
if (text === null) {
// An error occurred
} else {
document.body.innerHTML += test;
}
});
}

Categories