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>
Related
I am trying to create an HTML document that contains a button “Request color”. Whenever a user clicks on “Request color”, the page performs an Ajax POST request to the URL color-service.php. The color-service.php file handles the POST request and returns a JSON containing a random color, for example: { color: "red" }. The Ajax response is then used to change the background of the color.html page accordingly.
Current HTML:
<!Doctype HTML>
<html>
<head>
<title>Random Color Changer</title>
</head>
<body style="<? echo $color?>">
<h1>Random Color Generator</h1>
<p id="color"></p>
<button type="button" onclick="changeColor()">Request Color</button>
<script>
function changecolor() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById.color = this.responseText;
}
}
};
xhttp.open("GET", "color-service.php", true);
xhttp.send();
}
</script>
</body>
</html>
Current PHP:
<?php
$list = array('red', 'blue', 'yellow', 'pink', 'green');
$i = array_rand($list);
$color = $list[$i];
?>
<body style="background-color:<? echo $color?>">
Make sure you're using background-color otherwise the browser won't know what you want coloured and in order for $color to do anything, you need to define it before you use it in your HTML.
echo $color = $list[$i];
And make sure color-serivce.php actually returns the random colour using echo, otherwise it will just be a blank page.
document.body.style.backgroundColor = this.responseText;
The JavaScript attribute you need to use is .style.backgroundColor and you need to use otherwise the browser doesn't know what you want coloured. Just color on it's own won't work for what you want it to (it will set the colour of the text).
Also you've give your function two different names; in one case it says changeColor() and in another it doesn't have the capital 'C'.
There are several problems here, but what you want is this:
HTML
<!Doctype HTML>
<html>
<head>
<title>Random Color Changer</title>
</head>
<body id="fillme">
<h1>Random Color Generator</h1>
<p id="color"></p>
<script>
function changecolor() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "color-service.php", true);
xhttp.onload = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById('fillme').style.backgroundColor = this.responseText;
}
};
xhttp.send();
}
changecolor();
</script>
<button type="button" onclick="changecolor();">Request Color</button>
</body>
</html>
PHP
<?php
$list = array('red', 'blue', 'yellow', 'pink', 'green');
$i = array_rand($list);
$color = $list[$i];
echo $color;
?>
as u can see below I am trying to change part o f my page without reload all page using ajax but I am not gettign any response
I am working on local host xampp and both files are in same directory
I also tired to palce files on host and nothing happen
i did not get even an error while connecting to the database in the accdata.php file when I place them on server while there is no database
I trid a lost to change the way of ponting the url part of xmlhttp.open
like file:///C:/xml/dineshkani.xml
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
</head>
<body align="left">
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
<script>
function SendForm()
{
alert("Hello! SendForm start");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
alert("Hello! going to send ajax");
xmlhttp.open("POST","AccData.php", true);
xmlhttp.send(document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
alert(document.getElementById("AccNum").value);
alert("Hello! SendForm end");
}
</script>
</body>
</html>
accdata.php
<?php
alert("Hello! php start processing");
echo "start";
$AccountNumber = $_POST['AccNum'];
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
alert("Hello! connected to oracle");
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:AccNum';
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':AccNum', $AccountNumber); // binds the parameter
oci_execute($stid); // executes the query
echo $AccountNumber;
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>
The ajax function is only sending a value rather than a post variable with associated value. Try along these lines - tidied it up a little but the important bit is the name=value in the parameters send via ajax and setting the Content-Type header often helps with stubborn xhr requests.
The javascript needn't be in the body - hence I moved that to the head section of the document.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
<script>
function SendForm(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open( "POST", "AccData.php", true );
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send( 'AccNum='+document.getElementById("AccNum").value );
}
</script>
</head>
<body>
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
</body>
</html>
A basic ajax function which can be re-used merely changing the parameters when it gets called.
function ajax(method,url,parameters,callback){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response );
};
var params=[];
for( var n in parameters )params.push( n+'='+parameters[n] );
switch( method.toLowerCase() ){
case 'post':
var p=params.join('&');
break;
case 'get':
url+='?'+params.join('&');
var p=null;
break;
}
xhr.open( method.toUpperCase(), url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}
function cbaccdata(r){ document.getElementById('AccNum').innerHTML=r; }
function sendForm(){
ajax.call( this, 'post','accdata.php',{ 'AccNum':document.getElementById("AccNum").value },cbaccdata );
}
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);
};
Right now I have a program that uses AJAX to read in a XML file and a json file. The problem is once the user clicks one of these buttons the text stays on the page forever. I was wondering if there was a way to make a button that would delete the text and sort of start over. I tried making a reset button but it didn't work. Here is the code that I have. Thanks for the help in advance.
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml")
xmlHttp.send();
}
function getJSON() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>" + responseObject[i].name
+ " lived during the " + responseObject[i].pet
+ " period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<form>
<h3>Dinosaur Web Services</h3>
<div id="home"></div>
<button type="reset" value="Reset">Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();">JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();">XML Dinos</button>
</form>
</body>
</html>
You can empty the div before inserting the new value in it. Like below i have done for one of the div, and with same you can do to other.
Add this to your script
<script>
function reset() {
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = ""; // empty the div here
divObj.innerHTML = output;
}
</script>
and add this button in your HTML
RESET
Here you go:
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
document.getElementById('msg').style.display = "none";
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml");
xmlHttp.send();
}
function getJSON() {
document.getElementById('msg').style.display = "none";
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>"+responseObject[i].name + " lived during the " + responseObject[i].pet + " period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
function resetDivs(){
document.getElementById('msg').style.display = "block";
document.getElementById('dinoJSON').innerHTML = "";
document.getElementById('dinoXML').innerHTML = "";
}
</script>
</head>
<body>
<form>
<h3> Dinosaur Web Services </h3>
<div id="home"></div>
<div id="msg">Select a button</div>
<button type="reset" value="Reset" onclick="resetDivs();"> Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();"> JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();"> XML Dinos</button>
</form>
</body>
</html>
I would need some advice/assistance here. I'm trying to pass 2 variable to other page from a link using ajax but when i click the link, there is no response. Seem like my ajax is not working, would appreciate if anyone can assist here. Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="productshow.js"></script>
</head>
<body>
<?php
$sql = mysql_query ("SELECT * FROM espaceproduct WHERE email = 'jaychou#hotmail.com' ");
?>
<?php
$result1 = array();
$result2 = array();
$loopCount1 = 0;
$loopCount2 = 0;
while($row = mysql_fetch_array($sql))
{
$result1[] = $row['thumbnail'];
$result2[] = $row['id'];
$_SESSION['thumbnail'] = $result1;
//$url = "profileview.php?email=".$result1[$loopCount1].'&'. "id=".$result2[$loopCount2];
$loopproduct = $result1[$loopCount1];
$loopid = $result2[$loopCount2];
echo"<br/>"."<br/>";
echo '<a href="#" onClick="ajax_post($loopproduct,$loopid)" >'. $_SESSION['thumbnail'][$loopCount1] .'</a>'."<br/>" ;
$loopCount1++;
$loopCount2++;
}
?>
</body>
</html>
This my ajax page
function list_chats(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
document.getElementById("showbox").innerHTML = hr.responseText;
}
}
hr.open("GET", "productshow.php?t=" + Math.random(),true);
hr.send();
}
setInterval(list_chats, 500);
function ajax_post(la,ka){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "espaceproductinsert.php";
var kn = "add="+la+"&csg="+ka;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status1").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(kn); // Actually execute the request
document.getElementById("csg").value = "";
}
This is the page where the variables should be insert
<?php
$add = $_POST['add'];
$csg = $_POST['csg'];
$sql2 = mysql_query ("INSERT INTO espaceproduct ( storename,productname ) VALUES ('$add','$csg') ");
?>
Smiply Try this
function ajax_post(la,ka){
$.post("espaceproductinsert.php", { add:la, csg:ka},
function(data) {
alert(data);
});
}
In page 1 add this script appropriately
<script language="javascript" type="text/javascript">
var httpObject=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
}
function tranferData(){
var data1= document.getElementById('div1').value;
var data2= document.getElementById('div2').value;
var queryString = "?data1=" + data1;
queryString += "&data2=" + data2;
httpObject.onreadystatechange = function(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var error = document.getElementById('error');
var response = httpObject.responseText;
alert(response);
}
}
httpObject.open("GET", "page2.php"+queryString ,true);
httpObject.send(null);
}
</script>
You send the data using above script and recieve from another page
page 2
<?php
echo $_GET['data1'];
echo $_GET['data2'];
?>
and on the serverside do this
<?php
header('Content-Type: application/json');
echo json_encode($_GET); //for testing replace with array('key'=>$value);
?>