how to retrieve data from the selected years - php

Help me how to post value years form drop-down then it will load into JSON data using ajax. Fix my code please i am a student that love to learn more. I appreciate your contribution to check my code if it is wrong. I'm not familiar with ajax but I'm trying.
<script>
$(document).ready(function () {
getGraph();
function getGraph()
{
$.getJSON("bar_graph_query.php", function (result)
{
var chart = new CanvasJS.Chart("chartBar", {
animationEnabled: true,
theme: "light2",
title:{
text: "Summary Rent Profit"
},
axisY: {
title: "Total (RM)"
},
data: [{
dataPoints: result,
}]
});
chart.render();
});
}
$.("#years").onchange(function(){
getGraph();
});
});
</script>
Scripts ajax load data to json (bar_graph_summary.php)
<div class="label">Select Name:</div>
<select class="form-control" name="years" id="years" style="width: 120px" >
<option value="'">Select Years</option>
<?php
include('db_conn.php');
$query = $conn->query("SELECT YEAR(rent_date) as years FROM rent GROUP BY YEAR(rent_date)");
while($row = $query->fetch_assoc())
{
echo '<option value="'.$row['years'].'">'.$row['years'].'</option>';
}
?>
</select>
Dropdown to select years (bar_graph_summary.php)
<?php
include('db_conn.php');
$data_points = array();
$years = $_REQUEST['years'];
$query = mysqli_query($conn, "SELECT MONTHNAME(rent_date) as month, SUM(rent_total)as total FROM rent WHERE YEAR(rent_date)='$years' GROUP BY MONTH(rent_date)");
//$query = mysqli_query($conn, "SELECT MONTHNAME(rent_date) as month, SUM(rent_total)as total FROM rent GROUP BY MONTH(rent_date)");
while($row = mysqli_fetch_array($query))
{
$point = array("label" => $row['month'] , "y" => $row['total']);
array_push($data_points, $point);
}
echo json_encode($data_points, JSON_NUMERIC_CHECK);
?>
query data json (bar_graph_query.php)

Related

How can use SQL query to get values from DB in arrays for a line chart

I'm trying to fetch data from DB for a line graph using the below code.
<?php
$dataPoints = array(
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while($row1 = $result1->fetch_assoc()) {
array("y" => 25, "label" => "Sunday"), ?>
} } else { }
);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?php echo json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<script src="https://canvasjs.com/assets/script/canvasjs.min.js"></script>
<div id="chartContainer" style="height: 370px; width: 100%;"></div>
Using the above code it gives as error as Un-expected Syntax error, expecting ) instead of ; at $dataPoints line
However if i m to remove the sql query, graph plots with static data perfectly.
Any Help is greatly appreciated..
I have to commend you for keeping PHP code and JavaScript separate. This is a very good idea. However, if you want to fetch all records from MySQL using PHP and mysqli library you do not need to have any loop. You can just fetch everything into an array and then display with json_encode() in JavaScript.
<?php
// import your mysqli connection before
$result1 = $conn->query("SELECT * FROM chart_data_column WHERE value = 'now'");
$dataPoints = $result1->fetch_all(MYSQLI_ASSOC);
?>
<script>
window.onload = function () {
var chart = new CanvasJS.Chart("chartContainer", {
title: {
text: ""
},
axisY: {
title: ""
},
data: [{
type: "line",
dataPoints: <?= json_encode($dataPoints, JSON_NUMERIC_CHECK); ?>
}]
});
chart.render();
}
</script>
<?= is short for <?php echo
You put the entire query inside the array. You need to separate them. Also, you have "chart_data_column" where the table name should be.
$dataPoints = array();
$sql1 = "SELECT * FROM chart_data_column WHERE value = 'now'";
$result1 = $conn->query($sql1);
if ($result1->num_rows > 0) {
while ($row = $result1->fetch_assoc()) {
$dataPoints[] = $row;
}
}

How to loop in PHP and display all rows

So I have this problem in looping in PHP, I can't seem to display, it only displays the first row. I want to display all 18 places and at the same time all places have different counts/data each. I think I'm missing a lot in PHP.
//This part of code displays the names and counts the met conditions
$sql = "SELECT b.name as brgy0,(SELECT COUNT(brgy_id) FROM tbl_fire_info where YEAR(date_of_report)=$year AND MONTH(date_of_report)=$smonth and status=1 AND brgy_id=b.barangayID) as cnt FROM tbl_barangay as b";
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_assoc($result);
$numData = $row['cnt'];
$brgyData = $row['brgy0'];
//This part of code displays the data in the graph, I decided to loop it 18 times
new Chart(document.getElementById("bar-chart-grouped"), {
type: 'bar',
data: {
labels: ['<?php if(isset($_POST['submit'])){echo $haz;} ?>'],
datasets: [ //barangays
<?php
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
?>
{
label: "<?php if(isset($_POST['submit'])){echo $brgyData;} ?>",
backgroundColor: "#3e95cd",
data: [<?php if(isset($_POST['submit'])){echo $numData;} ?>]
}
<?php
echo ",";
}
}else {
echo "0 results";
}
?>
]
},
options: {
title: {
display: true,
text: 'Number of reports'
}
}
});

Auto populate text fields based on dropdown selection where all values come from a MYSQL table

I'm trying to auto populate some text fields (rate1 and rate2) based on a dropdown selection (instid and instfirstname). The values are all in one mysql table called tbl_insts. I'm trying the solution found in How to Get Content in text field dynamically, based on dropdown selection in php, but can't get it to work. Does anyone have any suggestions? Thanks in advance.
This is my mysql table called tbl_insts
instid instfirstname rate1 rate2
1 john 50 45
2 eric 25 45
This is my html form. I'm able to populate the dropdown correctly but not the text fields.
<select name="instfilter" id="instfilter">
<?php
if ($stmt = $conn->prepare("select instid, instfirstname from tbl_insts order by instid")) {
$stmt->execute();
$stmt->bind_result($instid, $instfirstname);
echo '<option value="-1" selected="selected">Please select...</option>';
while ($stmt->fetch()) {
echo '<option value="'.$instid.'">'.$instfirstname.'</option>';
}
$stmt->close();
}
?>
</select>
<!-- Fields that I want to populate based on the selection on top -->
<input type="text" name="rate1" id="rate1" />
<input type="text" name="rate2" id="rate2" />
This is my code before the tag
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">
</script>
<script>
$('#instfilter').change(function(){
var inst = $(this).val();
$.ajax({
type:'POST',
data:{inst:inst},
url:'getrates.php',
success:function(data){
$('#rate1').val(data);
$('#rate2').val(data);
}
});
});
</script>
This is my code in getrates.php in the same directory as the html file above.
<?php
if (isset($_POST['inst'])) {
$qry = "select rate1, rate2 from tbl_insts where instid = ".
$_POST['inst'];
$rec = mysql_query($qry);
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1'];
echo $res['rate2'];
}
}
}
die();
?>
try change data:{inst:inst} to data:{'inst':inst}
now you returning a string from getrates.php. From you code structure, you can do like this:
if (mysql_num_rows($rec) > 0) {
while ($res = mysql_fetch_array($rec)) {
echo $res['rate1']."|".$res['rate2'];
}
}
..and
success:function(data){
var inputs = data.split('|');
$('#rate1').val(inputs[0]);
$('#rate2').val(inputs[1]);
}
hope this helps.
Untested, but I think these changes should do the job.
while ($res = mysql_fetch_array($rec)) {
$result = [
'rate1' => $res['rate1'],
'rate2' => $res['rate2']
];
}
.......
die(json_encode($result));
and
success: function(data){
data = $.parseJSON(data);
$('#rate1').val(data.rate1);
$('#rate2').val(data.rate2);
}

Select data based on value of ID

I am trying to select data based on a value, I have a form which selects data from a table of teams, I need to to get the ID of that row from the select dropdown (which I can do) but then use that to determine the data that it needs to select when im doing an AJAX request. Here goes:
Teams page - This page draws my graph which pulls in data via AJAX to draw the graph and its values:
<form action="teams.php?dashboard_id=<?php echo $dashboard_id; ?>" method="POST">
<select name="teamId">
<option selected="true" disabled="disabled">Please choose...</option>
<?php
$sql = "SELECT * FROM teams WHERE dashboard_id = $dashboard_id";
$result = $conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
echo '<option value=' . $row["team_id"] . '>' . $row["team_name"] . '</option>';
}
}
?>
</select>
<button class="compare">View</button>
</form>
<?php
if (!empty($_POST["teamId"])) {
$teamSelect = $_POST["teamId"];
echo $teamSelect;
}else{
echo "";
}
?>
<div style="max-width: 450px;">
<canvas id="mycanvas" class="container"></canvas>
</div>
Here is the PHP page that im doing the SELECT on:
<?php
include 'config.php';
$teamID = $_POST['teamId'];
$query = sprintf("SELECT
tm.member_id,
tm.team_id,
m.member_id,
m.firstName,
m.lastName,
m.score_1,
m.score_2,
m.score_3,
m.score_4,
m.score_5,
m.score_6,
m.score_7,
m.score_8,
m.dashboard_id,
t.team_id,
t.team_name,
t.dashboard_id
FROM team_members tm
JOIN members AS m
on m.member_id = tm.member_id
JOIN teams AS t
on t.team_id = tm.team_id
WHERE tm.team_id = '$teamID'"); // This need to be dynamic and got from the POST request on the form above.
$result = $conn->query($query);
$data = array();
foreach ($result as $row) {
$data[] = $row;
}
$result->close();
$conn->close();
header('Content-type: application/json');
print json_encode($data);
?>
Im drawing the graph out via another file:
$(document).ready(function(){
$.ajax({
url : "http://localhost/acredashAdv/teamData.php",
type : "GET",
success :function(data){
console.log(data);
var chartata = {
labels: [
"Strategic Development and Ownership",
"Driving change through others",
"Exec Disposition",
"Commercial Acumen",
"Develops High Performance Teams",
"Innovation and risk taking",
"Global Leadership",
"Industry Leader"
]};
var ctx = $("#mycanvas");
var config = {
type: 'radar',
data: chartata,
animationEasing: 'linear',
options: {
legend: {
display: true,
position: 'bottom'
},
tooltips: {
enabled: true
},
scale: {
ticks: {
fontSize: 15,
beginAtZero: true,
stepSize: 1
}
}
},
},
LineGraph = new Chart(ctx, config);
var colorArray = [
["#7149a5", false],
["#58b7e0", false],
["#36bfbf", false],
["#69bd45", false],
["#5481B1", false],
["#6168AC", false]
];
for (var i in data) {
tmpscore=[];
tmpscore.push(data[i].score_1);
tmpscore.push(data[i].score_2);
tmpscore.push(data[i].score_3);
tmpscore.push(data[i].score_4);
tmpscore.push(data[i].score_5);
tmpscore.push(data[i].score_6);
tmpscore.push(data[i].score_7);
tmpscore.push(data[i].score_8);
var color, done = false;
while (!done) {
var test = colorArray[parseInt(Math.random() * 6)];
if (!test[1]) {
color = test[0];
colorArray[colorArray.indexOf(test)][1] = true;
done = !done;
}
}
newDataset = {
label: data[i].firstName+' '+data[i].lastName,
borderColor: color,
backgroundColor: "rgba(0,0,0,0)",
data: tmpscore,
};
config.data.datasets.push(newDataset);
}
LineGraph.update();
},
});
});
This is all great but in my select query I need the WHERE clause to show me data determined on the value of the team ID and not a static value but im not sure how to pass across the ID from the select back to the AJAX file?
Use sessions then. $_SESSION['teamID'] = $teamID. Then you can reference it anywhere. Be sure to start the session at the top of each php file using sessions.
session_start();
$teamID = $_POST['teamId'];
$_SESSION['teamID'] = $teamID;
References:
http://php.net/manual/en/function.session-start.php
http://php.net/manual/en/book.session.php

multiple selector ajax request showing error and how to get the selected value from multiple select box?

The following is my code.My work is, based on city, location change.So once I select city one Ajax request will send and location will reset.This location is multiple select box so I can select multiple location.based on this I want to show the branches.Here my problem is when I am changing the city multiple drop down is coming.and when I am printing
alert($('#cboLocation option:selected').val()) its only alerting 1st value
PHP code
<?php
$arrCity = array('Chennai' => 'Chennai',
'Delhi' => 'Delhi',
'Noida' => 'Noida');
$act = formatstring($_POST['act']);
switch($act)
{
case "getCommonLocation":
$dbConn = setDbConn();
$strCityName = $_POST['CityName'];
$strSQL = "SELECT distinct locality
FROM mp_new_project
WHERE city = '".$strCityName."' ORDER BY locality ASC";
$stmt = $dbConn->prepare($strSQL);
$stmt->execute();
// $stmt->bind_result($LocationId, $Location);
$stmt->bind_result($Location);
while($stmt->fetch())
//$arrLocations[] = array($LocationId, $Location);;
$arrLocations[] = array($Location);
for($i=0;$i<count($arrLocations);$i++)
$strOptionsList .= "<option value='".$arrLocations[$i][0]."'>".$arrLocations[$i][0]."</option>";
$stmt->close();
$dbConn->close();
print "<option value='all'>All</option>".$strOptionsList;
exit();
break;
}
?>
Javascript
<script type="text/javascript" src="scripts/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="scripts/jquery-ui-1.8.13.custom.min.js"></script>
<script type="text/javascript" src="scripts/ui.dropdownchecklist-1.4-min.js"></script>
<script type="text/javascript">
function chnageToUP()
{
// var selLoc = $('#cboLocation option:selected').text();
alert($('#cboLocation option:selected').val());
return false;
}
function getCommonLocationForCities()
{
url = 'testing1.php';
strCityName = $('#cboCity').val();
//chnageToUP();
$.post(
url,
{
"act" : "getCommonLocation",
"CityName" : strCityName
},
function(responseText){
$('#cboLocation').val("");
$('#cboLocation').html(responseText);
$("#cboLocation").dropdownchecklist({firstItemChecksAll: true,
maxDropHeight: 100,
onComplete: function(selector)
{
chnageToUP();
}});
},
"html"
);
}
</script>
HTML Code
<table style="margin-left:50px;" cellpadding="3" cellspacing="1" border="0" >
<tr>
<td><b>City</b></td>
<td><select name="cboCity" id="cboCity" onchange="getCommonLocationForCities()">
<option value="">City</option>
<?php
foreach($arrCity as $item)
{
print "<option value='".$item."'>".$item."</option>";
}
?>
</select></td>
</tr>
<tr>
<td><b>Location</b></td>
<td>
<select name="cboLocation" id="cboLocation" class="select_142" multiple="multiple">
<option value='location'>Location</option>
</select>
</td>
</tr>
</table>
following is the link
http://vignesh.gvignesh.org/dropdown/
use map to get the checked values in an array....
try this
function chnageToUP()
{
var tempArray="";
tempArray=$('#cboLocation :checked').map( function() { return this.value; });
console.log(tempArray);
return false;
}
alert() is not such a good debugging method, use console.log() instead. Requires you to have Firebug or Google Chrome though to see the contents.

Categories