Generating a chart using JS libraries - javascript

The following set of codes are used to generate a chart using fusionchart javascript library!
This is the php script
<?php
//address of the server where db is installed
$servername = "localhost";
//username to connect to the db
//the default value is root
$username = "chart";
//password to connect to the db
//this is the value you would have specified during installation of WAMP stack
$password = "L12345d";
//name of the db under which the table is created
$dbName = "test";
//establishing the connection to the db.
$conn = new mysqli($servername, $username, $password, $dbName);
//checking if there were any error during the last connection attempt
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//the SQL query to be executed
$query = "SELECT * FROM top_odi_wicket_takers";
//storing the result of the executed query
$result = $conn->query($query);
//initialize the array to store the processed data
$jsonArray = array();
//check if there is any data returned by the SQL Query
if ($result->num_rows > 0) {
//Converting the results into an associative array
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['player'];
$jsonArrayItem['value'] = $row['wickets'];
//append the above created object into the main array.
array_push($jsonArray, $jsonArrayItem);
}
}
//Closing the connection to DB
$conn->close();
//set the response content type as JSON
header('Content-type: application/json');
//output the return value of json encode using the echo function.
echo json_encode($jsonArray);
?>
This is the json script
$(function() {
$.ajax({
url: 'http://localhost/GP/Charts/chart_data.php',
type: 'GET',
success: function(data) {
chartData = data;
var chartProperties = {
"caption": "Top 10 wicket takes ODI Cricket in 2015",
"xAxisName": "Player",
"yAxisName": "Wickets Taken",
"rotatevalues": "1",
"theme": "zune"
};
apiChart = new FusionCharts({
type: 'column2d',
renderAt: 'chart-container',
width: '550',
height: '350',
dataFormat: 'json',
dataSource: {
"chart": chartProperties,
"data": chartData
}
});
apiChart.render();
}
});
});
The follwoing code gives the html code
<!DOCTYPE html>
<html>
<head>
<title>Fusion Charts Column 2D Sample</title>
</head>
<body>
<div id="chart-container">FusionCharts will render here</div>
<script src="js/jquery-2.1.4.js"></script>
<script src="js/fusioncharts.js"></script>
<script src="js/fusioncharts.charts.js"></script>
<script src="js/themes/fusioncharts.theme.zune.js"></script>
<script src="js/app.js"></script>
</body>
</html>
According to the tutorial i followed it should generate the chart when the html code is executed! But when its executed no chart apperas but only a text stating
"FusionCharts will render here" appears how can i correct the code inorder to generate the chart? i followed this tutorial exaclty http://www.fusioncharts.com/dev/using-with-server-side-languages/tutorials/php-mysql-charts.html

I guess you have not installed the jquery properly. Click here to download jquery and copy that under the above created js folder.

require('http://localhost/GP/Charts/chart_data.php'')
should be
require('http://localhost/GP/Charts/chart_data.php')

i think u should keep all the script files inside the head tag so that they load before the dom(div) loads..give it a try

Related

How to fetch data from MYSQL with AJAX from PHP

i want to call my array data from database using ajax. but i don't know the way. im confused in ajax call to show it into text field. how to get array data from my sql query
this the index.php looks like..
<body>
<div class="container" >
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "POST",
url: "getword.php",
dataType: "json",
cache: false,
success: function(result){
$('#wordlist').html(result[0]);
}
});
});
});
</script>
</body>
and then this is the url getword.php looks like
<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "wordlist";
$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select kata from word";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
$result[]= $row[0];
}
echo json_encode(array('kata'=>$result));
mysqli_close($con);
?>
id="wordlist" is an input, what you passing back from the API is a object
{
kata: [...]
}
So $('#wordlist').html(result[0]); wont work, your need to use $('#wordlist').val(result.kata[0]); (note: val not html) for first item, else it will join the values word1,word2,word3 etc
If your intention is not to place all words in a single input then you should change it so it loops over result.kata and creates an input for each word etc
I would like to suggest you to debug your code by yourself using following steps :
1.You can check what response you are getting from server side by printing your ajax response data at console to print this use below code.
success: function(result){
console.log(result);
// $('#wordlist').html(result[0]);
}
This will print that you are receiving data from server side.
2.Another point is you are handling the response inside an input field if want to print fetch data inside input field then you have to replace $('#wordlist').html(result[0]); from $('#wordlist').val(result[0]); this line from your JavaScript code because it is an input field.

Jquery/Ajax to get database using php

I have an HTML page that is too big to post on here, however I'll just post the ajax/jquery I am using to try and access the PHP file variables.
threadPage.html
<script type="text/javascript">
$.ajax({
url : '/ThreadCreation.php',
type : 'POST',
data: {'titles': titles}
crossDomain: true,
dataType : 'jsonp',
success : function (data) {
console.log(data) /
},
error : function () {
alert("error");
}
})
</script>
<!-- bunch of html -->
So essentially I am trying to get the variable from the ThreadCreation.php in JSON form. It should be in an array so that I can loop through it in the HTML file.
ThreadCreation.php
<?php
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$sql = mysqli_query($conn, "SELECT title FROM thread");
while($row = mysqli_fetch_array($sql)) {
$titles[] = $row['title'];
echo json_encode($titles);
?>
I will repeat though, that this HTML file is only getting information from the database through PHP. So there is no form submission here.
I keep getting that 'titles is not defined'. This makes sense because there is not titles defined in the HTML, however I am unsure how to construct my ajax request to collect the data, as this format is all I have seen people use.
Mention empty array first just to prevent error in case you have no data
in database then empty array will proceed.
$sql = mysqli_query($conn, "SELECT title FROM thread");
$titles = array();
while ($row = mysqli_fetch_array($sql)) {
array_push($titles,$row['title']); // Push data in empty array
}
echo json_encode($titles);

Ajax request : get text from database and display in div

My goal is to perform an AJAX request when clicking on a button to retrieve "name" and "story" stored in my database. Each button will get info of another hero.
I'm working on multiple files.
With my current code (which is the closer to what seems to be correct in my mind) the switchHeroInfo will always change the text to "TestName" and "StoryName" instead of "Gertrude" "An old lady"(stored in database).
Can you enlight me on what may be the cause of my struggles?
the php file for connecting to database : connect_database.php
<?php
try
{
$bdd = new PDO('mysql:host=localhost;dbname=biomass;charset=utf8', 'root', '', array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION));
}
catch(Exception $e)
{
die('Error : '.$e->getMessage());
}
?>
The Javascript part :
$(document).ready(function()
{
$(".hero_portrait").click(function()
{
var index = $(this).data("id");
$.ajax(
{
type: "POST",
url: "../php/get_data.php",
data: {newIndex:index},
success: function(data)
{
// Display {"nick":"Gertrude","0":"Gertrude","story":"Vieille folle senile","1":"Vieille folle senile"}
alert(data);
//Display : undefined
alert(data.story);
$("#hero_name").html(data.nick);
$("#hero_story").html(data.story);
},
error: function()
{
alert("Request failure");
}
});
});
});
The php file : get_data.php
<?php
$tempValue = $_POST['newIndex'];
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = :indexValue');
$sql->bindParam(":indexValue", $tempValue, PDO::PARAM_STR);
$sql->execute();
while($data = $sql->fetch())
{
?>
<script>
$heroNameTemp = <?php echo json_encode($data["name"]); ?>;
$heroStoryTemp = <?php echo json_encode($data["story"]); ?>;
</script>
<?php
}
$sql->closeCursor();
?>
Finally the HTML relative to the current problem:
<div id="squad_portraits">
<div class="hero_portrait" id="1"></div>
<div class="hero_portrait" id="2"></div>
<div class="hero_portrait" id="3"></div>
<div class="hero_portrait" id="4"></div>
</div>
<div id="hero_info">
<h2 id="hero_name">Hero_Name</h2>
<p id="hero_story"> Hero_Description</p>
</div>
If i switch my sql request :
$tempValue = $_POST['newIndex'];
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = :indexValue');
to this
$tempValue = 4;
$sql = $bdd->prepare('SELECT * FROM heroes WHERE ID = 4');
AND add the following to my HTML file
<?php include("../php/get_data.php"); ?>
everything works but my index will always be "4".
There are several issues and missunderstandings in your code.
first, in ajax change data to this:
data: {newIndex:index}, // remove the (), simple syntax misstake
This should solve the sql problem.
Now the get_data.php:
<?php
// including db connection is missing here for $bdd
// You should add a test here, wether you've received any and correct data in 'newIndex'
if(empty($_POST['newIndex']) {
// throw an error, send that back to ajax (with a fitting http response code) and exit script
http_response_code(400);
$error = new stdClass();
$error->msg = "Parameter newIndex was missing";
header('Content-Type: application/json'); // tell the browser that there is some json coming!
echo json_encode($error);
exit;
}
$tempValue = $_POST['newIndex'];
// only select the values you need (name, story)
$sql = $bdd->prepare('SELECT name, story FROM heroes WHERE ID = :indexValue');
$sql->bindParam(":indexValue", $tempValue, PDO::PARAM_STR);
$sql->execute();
$data = $sql->fetch(); // if you only expect/need one row, no while is needed
// echo ONE json string as plain string:
header('Content-Type: application/json'); // tell the browser that there is some json coming!
echo json_encode($data);
Now you receive content of $data as a json as param (data) in the success-callback of your ajax, which you can use like this:
success: function(data){
$("#hero_name").html(data.name);
$("#hero_story").html(data.story);
}
Finally let's change storing the item's id from the id attribute to the data-attribute:
In html:
<div class="hero_portrait" data-id="1"></div>
<div class="hero_portrait" data-id="2"></div>
and in javascript change
var index = $(this).attr("id");
to
var index = $(this).data("id"); // $(this).attr("data-id"); will also work

How to query to DB & plot the values on dashboard dynamically?

I'm very new to dashboard stuffs.Learning PHP & javascript. I'm trying to create a pie-chart with the help of already available google-chart. I could able to make it (Because, data is hard coded). I'm trying same to plot the pie-chart with dynamic values (querying to DB & plot the values on pie-chart). I'm trying to do it, but couldn't. Could you please help me to achieve this (MySQL, say 2 columns Name & Score).
Working code [For static data]:
<html>
<head>
<script type="text/javascript" src="loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
**var data = google.visualization.arrayToDataTable([
['Task', 'Hours per Day'],
['Work', 11],
['Eat', 2],
['Commute', 2],
['Watch TV', 2],
['Sleep', 7]
]);**
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
I understand above highlighted part does the work of loading static data.
Tried embedding above script with db related PHP. Probably, i might be missing to call it in right way. Could you please help me to provide the missing interface. I'm very new to all these technologies.
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbName = "test";
$conn = new mysqli($servername, $username, $password, $dbName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$query = "SELECT * FROM student";
$result = $conn->query($query);
$jsonArray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$jsonArrayItem = array();
$jsonArrayItem['label'] = $row['Name'];
$jsonArrayItem['value'] = $row['Scores'];
array_push($jsonArray, $jsonArrayItem);
}
}
$conn->close();
header('Content-type: application/json');
echo json_encode($jsonArray);
?>
Intoduction
Ok, if your code works correctly I suppose currently you have made a php script that spits out a JSON document in the format you need.
Now you need to actually load the data with javascript and feed it into the charting API.
So instead of feeding the hardcoded array at var data = google.visualization.arrayToDataTable you need to load it from the php script.
Have a look at the following links that solve this problem either with pure JS or with JQuery:
How to get JSON from URL in Javascript?
http://codepen.io/KryptoniteDove/post/load-json-file-locally-using-pure-javascript
Example with JQuery
Keep in mind calls are asynchronous so you need to have your charting logic triggered in ( or by ) the listener that handles the ajax call.
$.getJSON('http://localhost/myApp/myScript.php&callback', function(data) {
var data = google.visualization.arrayToDataTable(data);
var options = {
title: 'My Daily Activities'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
});

Why can't I import a var from php to js using ajax?

I'm trying to work with ajax, but I'm stuck, because I tried various things to import a var from a php file to js. What am I supposed to write after the success: function() to import $rowcount to js? I know that there are already some questions and answers on the site, but none of those seems to work...
Here's the php code:
<?php
$host = "localhost";
$user = "root";
$pw = "";
$dbName = "mathgame";
$tblName = "fragen";
// mit mysql db verbinden
$con = mysqli_connect($host, $user, $pw, $dbName);
if ($con->connect_error) {
die ("Connection failed: " . $con->connect_error);
}
// Datenanfrage an db
$result = mysqli_query($con, "select id from $tblName where Kategorie='Kategorie1'");
$rowcount = mysqli_num_rows($result);
json_encode($rowcount);
?>
And the js code:
<script id="source" language="javascript" type="text/javascript">
$.ajax({
url: 'Kategorie1.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(){
}
})
json_encode() returns a string but your code does nothing with the value. All you need to do is write the return value to stdout. One way to do that is:
echo json_encode($rowcount);
You would need to take in the data that is returned from your PHP script.
Add the data after success: function( for you to manipulate and use the return data.
<script id="source" language="javascript" type="text/javascript">
$.ajax({
url: 'Kategorie1.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(data) {
console.log(data); // outputs the json data into your console
}
})
$.getJSON("Kategorie1.php", function (data) {
var nrFragen = JSON.parse(data);
That's the js code, which worked for me, and of course at the end of the php code there should be : echo json_encode($rowcount);

Categories

Resources