Reputation: 902
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
Upvotes: 3
Views: 971
Reputation: 503
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
Upvotes: 3