Once again about how to plot google chart after an ajax call - javascript

EDIT BEGIN
As I didn't receive any answer I'll try to explain or, better, show what worked to me (without ajax) and doesn't work now when I try to use ajax. As examples say more than words I'll write down the essencial parts of the codes.
I had two files, namely index.php where is the input form and where the chart is plotted and script.php that receives what was inserted in the form, makes a query with it and return a variable that goes back to index.php to just be used in the Google stuff.
So here you are:
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Google Charts -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"],callback:drawChart01});
google.setOnLoadCallback(drawChart01);
// CHART 01
function drawChart01() {
var data = google.visualization.arrayToDataTable([
['Technological Area', 'Number of Publications'],
<?php echo $_SESSION['techAreas03']; ?>
]);
var options = {
chartArea: {width:'100%',height:'100%'},
forceIFrame: 'false',
is3D: 'true',
pieSliceText: 'value',
sliceVisibilityThreshold: 1/20, // Only > 5% will be shown.
titlePosition: 'none'
};
var chart = new google.visualization.PieChart(document.getElementById('tech-areas'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form id="publn-nr-srch" action="script.php" method="post" role="form">
<input id="publn-in" name="publn-in" placeholder="Publication Number" type="text" required />
<input id="btn-srch" type="submit" value="Search">
</form>
<?php
if(isset($_SESSION['techAreas03'])){
echo '<div id="tech-areas"></div>';
}
?>
</body>
</html>
and the script.php:
<?php
session_start();
# Query
$sql = "SELECT techarea FROM $table WHERE publn = :publn";
$q = $conn->prepare($sql);
$q->execute(array(':publn' => $_POST['publn-in']));
while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
$techAreas00[] = ($r['techarea']);
}
# Separate values of the array that are together in only one field and put them into another array.
$techAreas01 = explode(', ', implode(', ', $techAreas00));
# Count values.
$techAreas02 = array_count_values($techAreas01);
# Sort array.
arsort($techAreas02);
# Transform array in a string that will be used in GOOGLE CHART.
$techAreas03 = implode(', ', array_map(function ($v, $k) { return '[\''.$k.'\','. $v.']'; }, $techAreas02, array_keys($techAreas02)));
$_SESSION['techAreas03'] = $techAreas03;
# Reload index.php, but now with the variable $techAreas03 that will be used in the head to populate the GOOGLE CHART.
header(Location: index.php);
This work just fine.
Now when I try to use ajax to avoid that my index.php reloads I'm unable to plot the charts. The problem is that the Google script was already loaded before the script.php creates the variable. More about the problem in the original answer below.
And here are the codes of the modified pages:
index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Google Charts -->
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"],callback:drawChart01});
google.setOnLoadCallback(drawChart01);
// CHART 01
function drawChart01() {
var data = google.visualization.arrayToDataTable([
['Technological Area', 'Number of Publications'],
<?php echo $techAreas03; ?>
]);
var options = {
chartArea: {width:'100%',height:'100%'},
forceIFrame: 'false',
is3D: 'true',
pieSliceText: 'value',
sliceVisibilityThreshold: 1/20, // Only > 5% will be shown.
titlePosition: 'none'
};
var chart = new google.visualization.PieChart(document.getElementById('tech-areas'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form id="publn-nr-srch" action="" method="post" role="form">
<input id="publn-in" name="publn-in" placeholder="Publication Number" type="text" required />
<input id="btn-srch" type="submit" value="Search">
</form>
<div id="ajax"></div>
</body>
<script type="text/javascript">
$(function(){
$('form#publn-nr-srch').submit(function(){
$.ajax({
url: 'script.php',
type: 'POST',
data: $('form#publn-nr-srch').serialize(),
success: function(response) {
$('div#ajax').html(response);
}
});
return false;
});
});
</script>
</html>
and here the script.php:
<?php
session_start();
# Query
$sql = "SELECT techarea FROM $table WHERE publn = :publn";
$q = $conn->prepare($sql);
$q->execute(array(':publn' => $_POST['publn-in']));
while ($r = $q->fetch(PDO::FETCH_ASSOC)) {
$techAreas00[] = ($r['techarea']);
}
# Separate values of the array that are together in only one field and put them into another array.
$techAreas01 = explode(', ', implode(', ', $techAreas00));
# Count values
$techAreas02 = array_count_values($techAreas01);
# Sort array.
arsort($techAreas02);
# Transform array in a string that will be used in GOOGLE CHART.
$techAreas03 = implode(', ', array_map(function ($v, $k) { return '[\''.$k.'\','. $v.']'; }, $techAreas02, array_keys($techAreas02)));
I my research about the issue I found many threads that talked about the call back function to plot the chart with ajax, but if we've already have the data that build the chart. The problem is that I didn't find any answer specific to my issue, because I have to send another data via ajax (namely the publication number = publn-in) the begins a query and the result of this query is the data that will be used by Google chart.
I hope I could be a little bit more intelligible now and that you guys can help me.
As already said, more info below and at any time you can ask more.
Many thanks!
EDIT END
ORIGINAL POST BEGIN
I have a form which I use to send info to a php script through ajax.
This script get this info, queries database and give me back an array which I transform in a string.
This string would be used to plot google chart.
I searched how I could plot the chart after a ajax call, but I was unable to get the expected results.
The problem is that the is already loaded and we have to use a callback to plot the chart.
Here my code:
<html>
<head>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart04);
function drawChart04() {
var data = google.visualization.arrayToDataTable([
['Publication', 'Similarity'],
<?php echo $chart; ?>
]);
var options = {
chartArea: {width:'80%',height:'80%'},
forceIFrame: 'true',
titlePosition: 'none',
hAxis: {title: 'Most Similar Publications', textPosition: 'none'},
legend: {position: 'none'}
};
var chart = new google.visualization.LineChart(document.getElementById('sim-curve'));
chart.draw(data, options);
}
</script>
</head>
<body>
<form id="publn-nr-srch" action="" method="post" role="form">
<input class="form-control" id="publn-in" name="publn-in" placeholder="Publication Number" type="text" value="" required />
<input id="btn-srch" class="btn btn-sm btn-primary" type="submit" value=" Search ">
</form>
<div id="ajax"></div>
</body>
<script type="text/javascript">
$(function(){
$('form#publn-nr-srch').submit(function(){
$.ajax({
url: '../models/pubSearchScr.php',
type: 'POST',
data: $('form#publn-nr-srch').serialize(),
success: function(response) {
$('div#ajax').html(response);
}
});
return false;
});
});
</script>
</html>
After the script runs I receive, for example, following string in a variable (here everything runs well):
$chart = "['1977',8], ['1978',31], ['1979',48], ['1980',34], ['1981',30], ['1982',37], ['1983',28], ['1984',31], ['1985',40], ['1986',32], ['1987',44], ['1988',42], ['1989',45], ['1990',43], ['1991',36], ['1992',31], ['1993',34], ['1994',26], ['1995',25], ['1996',41], ['1997',35], ['1998',27], ['1999',25], ['2000',14], ['2001',31], ['2002',19], ['2003',16], ['2004',21], ['2005',20], ['2006',12], ['2007',16], ['2008',29], ['2009',10], ['2010',13], ['2011',22], ['2012',2], ['2013',2]";
which I use in the google stuff (seen above into head session as well - ):
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart04);
function drawChart04() {
var data = google.visualization.arrayToDataTable([
['Publication', 'Similarity'],
<?php echo $chart; ?>
]);
var options = {
chartArea: {width:'80%',height:'80%'},
forceIFrame: 'true',
titlePosition: 'none',
hAxis: {title: 'Most Similar Publications', textPosition: 'none'},
legend: {position: 'none'}
};
var chart = new google.visualization.LineChart(document.getElementById('sim-curve'));
chart.draw(data, options);
}
</script>
In the script, as well I have following variable that is echoed in the ende. In the ende I can see the html stuff on screen, but not the chart:
$output = '
<!-- Similarity Curve -->
<div class="col-md-6">
<div class="panel panel-default">
<div class="panel-heading">
<div class="panel-title">
<i class="fa fa-line-chart"></i>
Similarity Curve
</div>
</div>
<div class="panel-body">
<div id="sim-curve"></div>
</div>
</div>
</div>';
echo $output;
I understand the problem, that the head with google chart info is already loaded without the $chart variable before I run the ajax call. Then when I start it everything goes well, but the chart cannot be plotted. In my research I read about callback function, etc and I thought it was already in my code. If not, what exactely need in my case and WHERE? In head as well or in the middle of html code, or in the script?
One advice: When I do the same without ajax, namely using a html form that send info to the php script and the script is then redirect back to the file, everthing works fine, because the head is loaded once more with the entire page. My problem is when I have to use the amazing ajax.
Any help would be appreciate.
Many thanks in advance.
ORIGINAL POST END

Firstly, you should create a function that is used to draw the google chart with the data of chart is input.
Example: drawChart(inputData) = drawChart04(data);
Secondly, you create a variable that stores data of the chart:
//var inputData = your data;
var inputData = google.visualization.arrayToDataTable([
['Publication', 'Similarity'],
<?php echo $chart; ?>
]);
Thirdly, you have to know how to return data by using ajax on the server (PHP):
Example: dataChart = you query or to do something to get it;
echo json_encode(dataChart); exit; //This is just an example.
Fourthly, you have to know how to pass data from PHP to Javascript. I mean when you receive the response, you have to know how to build inputData base on the response.
$.ajax({url: "....php", type: "POST", dataType: "json", data:{..}})
.done(function(response){
inputData = response; //You have to convert response to inputData. Maybe Json.parse(response).
//I don't know, You have to know that you response. So find the best way to create inputData.
drawChart(inputData);//And finally call this function
});
That's it. I think that you can understand what I mentioned above. If you cannot fix this thing. Message me by my skype. I will fix it for you. SkypeID: jewelnguyen8

Related

Problem with the appearance of geographical area points in map with google graph

I try to appear some geographical data as points (spots) in a global map.When i run the code -in the browser- are appearded the statistical results as text , the global map but on the they are not appeared.Itis must noted that the main code was taken from the code which implement the piechart.In the follow lines i present the code:
<!doctype html public "-//w3c//dtd html 3.2//en">
<html>
<head>
<title>plus2net.com : Pie chart using data from MySQL table</title>
</head>
<body >
<?Php
//
require "connection.php";// Database connection
if($stmt = $link->query("SELECT Nationality_Name,Count FROM nationality_arrivals")){
echo "No of records : ".$stmt->num_rows."<br>";
$php_data_array = Array(); // create PHP array
echo "<table>
<tr> <th>Nationality_Name</th><th>Count</th></tr>";
while ($row = $stmt->fetch_row()) {
echo "<tr><td>$row[0]</td><td>$row[1]</td></tr>";
$php_data_array[] = $row; // Adding to array
}
echo "</table>";
}else{
echo $link->error;
}
//print_r( $php_data_array);
// You can display the json_encode output here.
echo json_encode($php_data_array);
// Transfor PHP array to JavaScript two dimensional array
echo "<script>
var my_2d = ".json_encode($php_data_array)."
</script>";
?>
<div id="chart_div"></div>
<br><br>
<a href=https://www.plus2net.com/php_tutorial/chart-database.php>Pie Chart from MySQL database</a>
</body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
<div id="chart_div"></div>
<br><br>
<a href=https://www.plus2net.com/php_tutorial/chart-database.php>Pie Chart from MySQL database</a>
</body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
'packages': ['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawMarkersMap);
function drawMarkersMap() {
var data = google.visualization.arrayToDataTable([
['Nationality_Name','string'],['Count','number']
]);
var options = {title:'plus2net.com : How the tutorials are distributed',
width:600,height:500};
// Instantiate and draw the chart
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
}
</script>
</html>

Send image from php server using ajax call

The short of what I'm trying to do is search for a file and display a picture from the server. The HTML has a simple search bar that allows you to type in a search term. The JavaScript uses an ajax request to call the PHP file, and the PHP finds the image on the server and sends it back to be displayed.
What happens right now is that the image isn't displayed, and I get an icon indicating some invalid image. The ajax call appears to be working, but I think the data I'm sending back isn't correct. I've been trying to search for it but everyone seems to have a different opinion on how to do it and it's kind of confusing.
HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"> </script>
<script src="search.js"></script>
<style type="text/css"></style>
</head>
</body>
<header>
<h1>My Page</h1>
</header>
<input type=text name="search" id="searchbox" placeholder="Search...">
<input type=button value="Search" id=search><br>
<div id="images"></div>
</body>
JavaScript
$(document).ready(function() {
$("#search").on('click', function(){
$.ajax({
url: '/search.php',
type: 'POST',
data: $("#searchbox").serialize(),
success: function(data) {
$('#images').append(data);
},
error: function() {
alert('failure');
}
});
});
});
PHP
<?php
if(isset($_POST['search'])) {
$searchterm = $_POST['search'];
$image = "images/".$searchterm.".jpeg";
echo '<img src="data:image/jpeg;base64,'.base64_encode($image).'">';
}
else {
echo 'Error: image not found';
}
PS. For the moment, I'm ignoring any sort of error checking, I'm just trying to get it working and assuming the input is all valid
SUGGESTIONS:
Try this link:
Image Data URIs with PHP
<?php
if(isset($_POST['search'])) {
$searchterm = $_POST['search'];
$image = "images/".$searchterm."jpeg";
$imageData = base64_encode(file_get_contents($image));
$src = 'data: '.mime_content_type($image).';base64,'.$imageData;
echo '<img src="', $src, '">';
...
Debug the actual HTTP traffic between your jQuery/Browser and your PHP/back-end server. You can use a tool like Telerek Fiddler or Firebug, among many others.
'Hope that helps!
Use file_get_contents it will display the image on browser.
$image = "images/".$searchterm.".jpeg";
echo '<img src="data:image/jpeg;base64,'.base64_encode(file_get_contents($image)).'">';
Please change the url property in the object, used in your .ajax() method call. The path to your search.php is incorrect.
$.ajax({
url: '/search.php',
goes to:
$.ajax({
url: './search.php',

Embed PHP into javascript with Ajax in order to store MySQL data in javascript objects

Have googled a solution for this question for quite some time and it seems a lot of people are asking about the same thing. Haven't found a good answer that works though.
What I want to do:
I have a simple database called "fruitStand". It has a single table called "fruitTable" which contains two columns:
**fruit** **cost**
apple 5
pear 4
banana 2
orange 6
I can easily fetch the rows with a PHP script and display the result directly on the screen. However, I want to be able to get the result into my javascript arrays so I can build some graphs based on it.
After considering this post, I decided to use Jquery Ajax to glue the HTML/javascript code with the PHP code. I'm using the two files below (index.html and getData.php) along with the database. This generates the following HTML output when I hit the "Get data!" button:
apple5pear4banana2orange6
Now to the actual question:
How could I modify the code so I'm able to return the results in js array/object form? I want it to look something like this:
array1 = ["apple", "pear", "banana", "orange"]
array2 = [5,4,2,6]
The ultimate goal is to use these arrays when plotting the interactive graphs (will later on add buttons to select fruits/cost).
The index.html file:
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "GET",
url: "getData.php",
dataType: "html",
success: function(response){
var store = $("#responsecontainer").html(response);
}
});
});
});
</script>
<body>
<table border="1" align="center">
<tr>
<td> <input type="button" id="display" value="Get data!" /> </td>
</tr>
</table>
<div id="responsecontainer" align="center"></div>
</body>
</html>
The PHP file:
<?php
mysql_select_db('fruitStand',$con);
$result=mysql_query("select * from fruitTable",$con);
$con=mysql_connect("localhost","root","password");
if (!$con){
die('Could not connect: ' . mysql_error());
}
while($data = mysql_fetch_row($result)){
echo "$data[0]";
}
?>
If I were wanting to share an array of data from php to Javascript, I would use JSON.
Format the array that you want it to be used in php, then use json_encode php method to convert the php array to JSON.
In the js, use JSON.parse to decode the JSON into a Javascript object.
<html>
<head>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
<?php $phpArray = array(); ?>
<?php $phpArray = array(array('fruit' => 'green', 'cost' => 10), array('fruit' => 'blue', 'cost' => 9),array('fruit' => 'red', 'cost' => 8), array('fruit' => 'yello', 'cost' => 7));?>
<script>
var fruit = [];
var cost = [];
var jsString = '<?php echo json_encode($phpArray);?>';
var jsArray = JSON.parse(jsString);
for(var i in jsArray){
fruit[i] = jsArray[i]['fruit'];
cost[i] = jsArray[i]['cost'];
}
console.log(fruit);
console.log(cost);
</script>
Expected console output:
["green", "blue", "red", "yello"]
[10, 9, 8, 7]
this should help you get started. Loop through PHP NOT JAVASCRIPT.
<script>
<?php
$i = 0;
while($row = mysql_fetch_array($result)){
echo "fruit[$i] = '" . $row['fruit'] . "';";
echo "cost[$i] = '" . $row['cost'] . "';";
$i++;
}
?>
</script>

AJAX cannot print elements onclick

I have got 2 files, one named index.php and one named api.php. I am trying to retrieve some data from my DB and I've done this simple example before trying to put the code into my project. In the api.php file I ve got the following:
$connessione=mysql_connect(DB_HOST,DB_USER,DB_PASS) or die(mysql_error());
$scelta_db=mysql_select_db(DB_NAME) or die(mysql_error());
$idM=67;
$result = mysql_query("SELECT * FROM map_comment WHERE idMap ='$idM'");
$array = array();
while ( $row = mysql_fetch_row($result) )
{
$array[] = $row;
}
echo json_encode($array);
While in the index.php:
<html>
<head>
<script language="javascript" type="text/javascript" src="jquery.js"></script>
</head>
<body>
<h3>Output: </h3>
<div id="output">Attacco qua sotto</div>
<button onclick ='show_comments'>Carica commenti </button>
<script id="source" language="javascript" type="text/javascript">
function show_comments()
{
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(rows)
{
for (var i in rows)
{
var row = rows[i];
var idU = row[1];
var text_map = row[3];
$('#output').append("<b> idU: </b>"+idU+"<b>text </b>"+text_map)
.append("<hr />");
}
}
});
};
</script>
</body>
</html>
The problem is that it does not seems to "append" nothing and I dunno what I am doing wrong. I KNOW I should use mysqli, I'll fix that. Plus: HOW can I "send" a $idM to the api.php from the index.php (for example an $id already defined in the index.php)?
Your function is not called when you click the button, in an onclick attribute you're not setting a function but rather writing code to execute. See example below
<button onclick ='show_comments()'>...
To send the id, you can use the data parameter
data: {id: 67},
Since this is a GET request you can use the php super global $_GET to retrieve the value $_GET['id'].

retrieve data from mongodb and visualize it with google charts

I'd like to retrieve data from database (mongodb) and with those data i'd like to draw à pie chart using google charts. in a first case i have a collection called user and each user has a boolean attribute called (paid), i'd like to count how many paid users and free users and basing on those results i will draw a pie chart with the percentage of each kind of users
this my try i tried with for a long time but i'dont arrive to show the chart,
thanks :)
<?php
$connection = new MongoClient();
$collection = $connection->pato->user;
$cursor = $collection->find();
$cursor = $collection->find(array("paid"=>true));
$x=$cursor->count();
$cursor = $collection->find(array("paid"=>false));
$y=$cursor->count();
$myurl[]="['Option','Value']";
$myurl[]=[['Free users', $y],['Paid users', $x]];
?>
<html>
<head>
<!--Load the AJAX API-->
<body>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<script type="text/javascript">
google.load('visualization', '1', {'packages':['corechart']});
google.setOnLoadCallback(drawChart);
function drawChart()
{
var data=google.visualization.arrayToDataTable([
<?echo(implode(",",$myurl));?>
]);
// Set chart options
var options = {'title':'User statistics',
'width':400,
'height':300};
// Instantiate and draw our chart, passing in some options.
chart = new google.visualization.PieChart(document.getElementById('userStatsDiv'));
google.visualization.events.addListener(chart, 'select', selectHandler);
chart.draw(data, options);
}</script>
<body>
<div id="usageStatsDiv" style="width:700; height:500"></div>
</body>
</html>
I think your problem is with your JSON:
var data=google.visualization.arrayToDataTable([
<?echo(implode(",",$myurl));?>
]);
It looks like you're trying to build the JSON string yourself. Let PHP do the work for you instead - use json_encode instead, like this:
var data=google.visualization.arrayToDataTable([
<?php echo json_encode($data); ?>
]);
You'll need to build your $data array so that it gives you the correct elements, but I think you'll find that the end result is cleaner and easier to understand.

Categories