I'm writing an AJAX code that gets input from the users, and outputs the results, and it works when I'm setting the variable called text inside the function, but when I'm passing it through it doesn't work. Please take a look, I've taken all the irrelevant codes out, so it's short.
Code when I'm not passing it through the parameter:
<script type = "text/javascript">
function process(){
text = 'userInput';
food = encodeURIComponent(document.getElementById(text).value);
}
</script>
<html>
<body onload="process()">
</body>
</html>
Code when I'm passing it through the parameter:
<script type = "text/javascript">
function process(text){
food = encodeURIComponent(document.getElementById(text).value);
}
</script>
<html>
<body onload="process('userInput')">
</body>
</html>
I did document.write both times to make sure that the variable is really 'userInput', and both times, whether I'm passing it through or setting it inside the function, it printed out fine, so I'm not sure what the problem is. If you know what's wrong, please let me know. Thank you.
The whole code:
functions.js:
var xmlHttp = createXmlHttpRequestObject();
//****************************************************************AJAX
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("Not xmlHttp!")else
return xmlHttp;
}
//****************************************************************AJAX
function process(IDName, passTo, output) {
if (xmlHttp.readyState == 0 || xmlHttp.readyState == 4) {
get = encodeURIComponent(document.getElementById(IDName).value);
xmlHttp.open("GET", passTo + get, true);
xmlHttp.onreadystatechange = handleServerResponse(output);
xmlHttp.send(null);
} else {
setTimeout('process()', 1000);
}
}
//****************************************************************AJAX
function handleServerResponse(output) {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById(output).innerHTML = message;
setTimeout('process()', 1000);
} else {
alert('xmlHttp.status does not equal 200!');
}
}
}
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.'!';
elseif ($food=='')
echo 'Enter a food';
else
echo 'Sorry punk we dont sell no '.$food.'!';
echo '</response>';
?>
test5.html:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="functions.js"></script>
</head>
<body onload="process('userInput','foodstore.php?food=','underInput')">
<h3>The Chuff Bucker</h3>
Enter the food you would like to order:
<input type="text" id="userInput" />
<div id="underInput" />
</body>
</html>
I just ran this test on your (modified) code and it worked as expected.
<script type = "text/javascript">
function process(text){
alert(text);
food = encodeURIComponent(document.getElementById(text).value);
alert(food);
}
</script>
<html>
<body onload="process('userInput')">
<input id="userInput" value="yummy" />
</body>
</html>
You're performing handleServerResponse(output); when you assign the onreadystatechange handler, not when the event occurs. You need to delay calling the function until the event occurs:
xmlHttp.onreadystatechange = function() {
handleServerResponse(output);
};
Related
I am a newbie on TeeChart for PHP.
All examples I have found are rendering the chart on the same php file where it has been created.
I would like to build the chart using a PHP script, which receives some parameters via AJAX, and render the chart on the page which has generated the AJAX call.
Is that possible? Any example on that?
Best regards.
Jayme Jeffman
Here a simple example:
getchart.php:
<?php
// get the q parameter from URL
$q = $_REQUEST["q"];
//Includes
include "../../sources/TChart.php";
$chart1 = new TChart(600,450);
$chart1->getChart()->getHeader()->setText($q);
$chart1->getAspect()->setView3D(false);
$line1 = new Line($chart1->getChart());
$line1->setColor(Color::RED());
$chart1->addSeries($line1);
// Speed optimization
$chart1->getChart()->setAutoRepaint(false);
for($t = 0; $t <= 10; ++$t) {
$line1->addXY($t, (10 + $t), Color::RED());
}
$chart1->getChart()->setAutoRepaint(true);
$chart1->render("chart1.png");
$rand=rand();
echo "chart1.png?rand=".$rand;
?>
Test.html:
<!DOCTYPE html>
<html>
<head>
<script>
function showChart(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var image = document.getElementById("get_img");
image.src = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "getchart.php?q="+str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<p><b>Enter the chart title below:</b></p>
<form>
Chart title: <input type="text" onkeyup="showChart(this.value)">
</form>
<p><img id="get_img" /></p>
</body>
</html>
spend hours to find what has gone wrong, but failed.. since I'm new to Ajax, so I've no idea what I'm seeing. really need you guys to find the bug.
HTML
<!doctype html>
<head>
<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" />
</body>
</html>
javascript :
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");
}
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(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==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');
}
}
}
PHP (I think this file caused the problem)
<?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. '!';
}else if($food == ''){
echo 'Enter a food name.';
}else
{
echo "no, we don't sell " .$food. "!";
}
echo '</response>';
?>
JavaScript is case sensitive. You've got some syntax errors due to improper casing on some of the objects you're trying to create:
ActiveXobject
should be
ActiveXObject
^
and
XmlHttpRequest
should be
XMLHttpRequest
^^
The end result is that you're trying to create things that don't exist, resulting in the xmlHttp variable that is always false or undefined.
Your object creation logic seems backward (should try to create the modern object when you can, do the IE thing only if necessary), and mis-capitalized.
Try:
if (window.XMLHttpRequest) {
try {
xmlHttp = new XMLHttpRequest();
} catch(e) {
xmlHttp = false;
}
} else {
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
}
I want to get data from php array and show it on same page. how to
import data from php array by using search box. This code not working properly.
What is th error of this code?
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 hoss!");
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(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==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 you want to buy';
else
echo 'Sorry we don't sell it '.$food'!';
echo '</response>';
?>
Index.html
<html><head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The foods </h3>
Order your foods:
<input type="text" id="Userinput"></input>
<div id="underInput"></div>
</body>
</html>
How to show array data by searching from search box
I have changed the code using jquery its simple . You can try it.
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(function()
{
$("#Userinput").keyup(function()
{
process();
});
$("#Userinput").keydown(function()
{
process();
});
$("#Userinput").focus(function()
{
process();
});
$("#Userinput").change(function()
{
process();
});
});
function process() {
var input_food = $("#Userinput").val();
$.ajax({
type: "GET",
url: "foodstore.php",
data: {food: input_food},
success: function(message)
{
$("#underInput").html('<span style="color:blue">' + message + '</span>');
},
error: function()
{
$("#underInput").html('<span style="color:red">Some error occured</span>');
}
});
}
</script>
</head>
<body >
<h3>The foods </h3>
Order your foods:
<input type="text" id="Userinput" ></input>
<div id="underInput"></div>
</body>
</html>
foodstore.php
<?php
if (!empty($_GET['food']))
{
$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 you want to buy";
else
echo "Sorry we don't sell it " . $food . "!";
}
else
{
echo "Enter a food you want to buy";
}
?>
I think its simple if you know jquery .And there was a simple error in php you did't escape the extra single quotes in (don't) so I used double quotes for echo statements. Copy paste and tell if this is it what you want or not.Got any doubt ask.
Here is my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onLoad="process()">
<h3>WELCOME to our online food store</h3>
Please type what you want to order:
<input type="text" id="userinput" ></input>
<div id="underInput"></div>
</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('tuna','bacon','beef','loaf','mutton');
if(in_array($food,$foodArray))
echo 'We do have'.' '.$food;
elseif($food=='')
echo 'type something dude!';
else
echo 'Sorry we dont sell'.' '.$food;
echo '</response>';
?>
JS
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else if(window.XMLHttpRequest)
{
try
{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert('cannot connect to database!');
}
else
{
return xmlHttp;
}
}
function process()
{
if(xmlHttp.readyState == 0 || xmlHttp.readyState == 4)
{
food = encodeURIComponent(document.getElementById("userinput").value);
xmlHttp.open("GET", "ajax.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;
xmlDocumnetElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHtml = "<span style='color:blue'" + message + "</span>";
setTimeOut('process()',1000);
}
}
else
{
alert('something went wrong');
}
}
Everything seems to be fine to me but I still keep getting the error 'xmlDocumentElement is not defined'. Seems like this is an error due to some parsing issues within javascript and php.. Please help me fix this error. thanks
try to use
window.setTimeOut('process', 1000);
I want to make a php ajax post.(post value without refresh the page) here is my code. It can return the value and show in <div id="msg"></div>, But I also want to use this value.
In #benhowdle89 's help, I made $name= "<div id='msg'></div>". but when I use echo $name, in the source code, I can see <div id='msg'></div>(html tag), this is not a pure value, so I tried to use strip_tags, but the value lost. it seems the left the ajax pointed div tag, the value also gone. Still waiting for help...
index.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
</script>
</head>
<body>
<?php
echo $name="<div id='msg'></div>";
$name1=strip_tags($name);
$name2 = explode("|",$name1);
$namea=$name2[0];
$nameb=$name2[1];
?>
<form name="user_info" id="user_info" method="post">
<input name="user_name" type="hidden" value="abc|def" /><br />
<input type="button" value="abc|def" onClick="saveUserInfo()">
</form>
</body>
value.php
<?php
echo $_POST["user_name"];
?>
This is what I want. post value from index.php, then get the value by self without refresh the page. one botton with two values, I want explode them and finally get $namea and $nameb. I want use them in other php part.
You can put the ajax response into a javascript variable, then you can manipulate it from there:
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
alert( myPhpVariable );
Here is a working javascript example (full code):
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
The PHP file would look like:
$postVar = $_POST["user_name"];
$postVarArr = explode('|', $postVar);
// will show abc
//echo $postVarArr['0'];
// will show def
echo $postVarArr['1'];
by including $name= "<div id='msg'></div>" and calling echo $name, you're just telling the program to store "" in the $name variable and then print what is stored in that variable. That's why you're getting the unwanted output.
not sure if you're having problems posting the value or showing it in the value, but you need to echo the variable where the userName is stored, may need to send that from the ajax to the php and set it to $name.