CodeIgniter and Google charts - dropdown based on mysql values - php

I am using code igniter, google charts with php and MySQL to display charts. It works using fixed query. I am trying to add a dropdown to display the chart based on the option (sql column "status") selected
Here is what I have so far. How can I modify this to accept dropdown values?
model.php
public function get_chart_data()
{
$query = $this->db->get($this->db_mgmt);
$this->db->select('rating, COUNT(rating) AS Count');
$this->db->from('db_mgmt');
$this->db->where('status =', $status);
$this->db->group_by('rating');
$query = $this->db->get();
$results['chart'] = $query->result();
}
controller.php
$this->load->model('model', 'chart');
public function index() {
$results = $this->chart->get_chart_data();
$data['chart'] = $results['chart'];
$this->load->view('index.php', $data);
}
view.php
<?php
foreach ($chart as $object) {
$open_all[] = "['".$object->rating."', ".$object->Count."]";
}
?>
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart_open);
function drawChart_open() {
// Create the data table.
var data = new google.visualization.DataTable();
data.addColumn('string', 'Rating');
data.addColumn('number', 'Count');
data.addRows([
<?php echo implode(",", $open_all);?>
]);
var options = {
pieSliceText: 'value-and-percentage',
};
var chart = new google.visualization.PieChart(document.getElementById('open_div'));
chart.draw(data, options);
}
<div id="open_div" class="chart"></div>
Thanks in advance!
UPDATE:
I have tried the below using ajax but it doesn't seem to work. I am definitely sure I am doing something wrong here but not sure where. Using Inspect in chrome also doesn't give any errors.
model.php
public function fetch_result($status)
{
$query = $this->db->get($this->db_mgmt);
$this->db->select('rating, COUNT(status) AS Status_Count');
$this->db->from('db__mgmt');
$this->db->where('status =', $status);
$this->db->group_by('rating');
$query = $this->db->get();
return $query;
}
controller.php
$this->load->model('model', 'chart');
public function mychart() {
if(!empty($_POST["val"])) {
$val=$_POST["val"];
$result_new=$this->chart->fetch_result($val);
$array = array();
$cols = array();
$rows = array();
$cols[] = array("id"=>"","label"=>" Rating","pattern"=>"","type"=>"string");
$cols[] = array("id"=>"","label"=>"Count","pattern"=>"","type"=>"number");
foreach ($result_new as $object) {
$rows[] = array("c"=>array(array("v"=>$object->risk_rating,"f"=>null),array("v"=>(int)$object->Status_Count,"f"=>null)));
}
$array = array("cols"=>$cols,"rows"=>$rows);
echo json_encode($array);
}
}
view.php
function drawChart_open_all(num) {
var PieChartData = $.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "dashboard/chart/mychart",
data:'val='+num,
dataType:"json"
}).responseText;
alert(PieChartData);
// Create the data table.
var data = new google.visualization.DataTable(PieChartData);
var options = {
pieSliceText: 'value-and-percentage',
};
var chart = new google.visualization.PieChart(document.getElementById('open_new'));
chart.draw(data, options);
}
<div><span> <b>Pie Chart<br /><br /></span></div>
<form>
<select name="status" onchange="drawChart_open_all(this.value)">
<option value="WIP">WIP</option>
<option value="Close">Close</option>
</select>
</form>
<div id="open_new" class="chart"></div>
Thanks in advance!!

I think the easiest thing would be to send a GET request with the <option> value
First, go back to your first version.
Next, send the value in your onchange event
function drawChart_open_all(num) {
location = "<?php echo base_url(); ?>" + "dashboard/chart/mychart?option=" + num;
}
Then in Model --
get_chart_data()
you should be able to access the value with --
$_GET['option']
use that to modify your query
here's an old answer with similar concept -- difference is it uses POST vs. GET
and a <form> with a <input type="submit"> button to send the request
How to pass JavaScript variables to PHP?

I managed to figure out what the problem was and used ajax in the end. #WhiteHat solution led to also in the right direction. Thanks for that!
model.php
public function fetch_result($status)
{
$query = $this->db->get($this->db_mgmt);
$this->db->select('rating, COUNT(status) AS status_count');
$this->db->from('db_mgmt');
$this->db->where('status =', $status);
$this->db->group_by('rating');
$query = $this->db->get();
$results_new = $query->result(); // <-- Forgot to add this!
return $results_new;
}
controller.php
$this->load->model('model', 'chart');
public function mychart() {
if(!empty($_POST['option'])) {
$val = $_POST['option'];
$result_new=$this->chart->fetch_result($val);
$array = array();
$cols = array();
$rows = array();
$cols[] = array("id"=>"","label"=>" Rating","pattern"=>"","type"=>"string");
$cols[] = array("id"=>"","label"=>"Count","pattern"=>"","type"=>"number");
foreach ($result_new as $object) {
$rows[] = array("c"=>array(array("v"=>(string)$object->rating),array("v"=>(int)$object->status_count)));
}
$array = array("cols"=>$cols,"rows"=>$rows);
echo json_encode($array);
}
}
view.php
function drawChart_open_all(status) {
var PieChartData = $.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>" + "dashboard/chart/mychart",
data: { 'option':status }, // <-- kept as option instead of val
dataType:"json",
global: false, // <-- Added
async:false, // <-- Added
success: function(data){ // <-- Added
return data; // <-- Added
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
}).responseText;
// Create the data table.
var data = new google.visualization.DataTable(PieChartData);
var options = { pieSliceText: 'value-and-percentage', };
var chart = new google.visualization.PieChart(document.getElementById('open_new'));
chart.draw(data, options);
}
<div><span> <b>Pie Chart<br /><br /></span></div>
<form>
<select name="status" onchange="drawChart_open_all(this.value)">
<option value="WIP">WIP</option>
<option value="Close">Close</option>
</select>
</form>
<div id="open_new" class="chart"></div>

Related

Return JSON Data from PHP and Ajax

In my web application just I trying to returning JSON data from MySQL database using PHP and AJAX query. This is where I follow a tutorial on internet. In case in my application it shows and error like;
data = "↵↵↵↵Notice: Undefined index: lymph in
C:\xampp\htdocs\Hospital\hospitalwebsite\test_query\fetch_count.php
on line 29
Here is my AJAX Code :-
<script>
$(document).ready(function () {
$('select').material_select();
$('#search').click(function () {
var id = $('#test_list').val();
if (id != '') {
$.ajax({
url: 'test_query/fetch_count.php', // Url to which the request is send
method: 'POST', // Type of request to be send, called as method
data: { id: id },
//dataType:"JSON",
success: function (data) {
$('#success_mes').fadeIn().html(data);
$('#test_info').css('display', 'block');
$('#1').text(data.WBC);
$('#2').text(data.lymph);
$('#3').text(data.Mid);
}
});
} else {
alert('sdsd');
$('#test_info').css('display', 'none');
}
});
});
</script>
Below is the PHP Code :-
<?php
session_start();
require_once "../phpquery/dbconnection.php";
if (isset($_POST['id'])) {
//$id = $_POST['id'];
$stmt = $con->prepare("SELECT * FROM testing_report WHERE testing_report_id = ? AND test_id='7' ");
$stmt->bind_param("s", $_POST['id']);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows === 0);
while ($row = $result->fetch_assoc()) {
$medRecords = json_decode($row['testing_results'], true);
if (is_array($medRecords) || is_object($medRecords)) {
foreach ($medRecords as $key => $object) {
$data["WBC"] = $object['WBC'];
$data["lymph"] = $object['lymph'];
$data["Mid"] = $object['Mid'];
}
}
}
echo json_encode($data);
}
?>
SQL schema
Really I am appreciating if someone can help me. Thank you
The issue is that your data structure is split over several array elements, something like...
[
{
"WBC": "1"
},
{
"lymph": "5"
}
]
so each loop round the array only has 1 piece of information. This code combines all of that data into 1 set of information using array_merge() and then extracts the data from the result.
I've also added ?? 0 to default the values to 0 if not present, there may be a better default value.
$data = [];
$medRecords = json_decode($row['testing_results'], true);
if (is_array($medRecords) || is_object($medRecords)) {
$medRecords = array_merge(...$medRecords);
$data["WBC"] = $medRecords['WBC'] ?? 0;
$data["lymph"] = $medRecords['lymph'] ?? 0;
$data["Mid"] = $medRecords['Mid'] ?? 0;
}
JQuery work file if the result be json:
$(document).ready(function(){
$('#search').click( function () {
$.ajax({
url: "https://reqres.in/api/users?page=2",
method: "GET",
success:function(data)
{
console.log("page:", data.page);
console.log(data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="search">Search</button>
i think you have to add correct header to your result:
<?php
header('Content-Type: application/json');
add this code into first line of your php page. then jQuery know result is json.

Filter Table data using Ajax in Codeignitor

I'm not able to filter table data using Ajax. When I select BANK CREDIT from drop down it should fetch employee details with modeofpay(table column) as "BANK CREDIT" and when I select NEFT it should display employee details with modeofpay(table column) as "NEFT". As of Now nothing happens when i select drop down.
Controller:
public function filter($key = '')
{
$this->load->helper('url');
if ( $key == 'BANK CREDIT' ) {
$this->load->model('JcMeetingExpense_model');
$data = $this->JcMeetingExpense_model->getCredit($key);
}
else
{
$this->load->model('JcMeetingExpense_model');
$data = $this->JcMeetingExpense_model->getNeft($key);
}
echo json_encode($data);
}
Model:
public function getCredit($key)
{
$sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
public function getNeft($key)
{
$sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
View:
<script type="text/javascript">
var paymode = $("#mode").change(function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("JcMeetingExpense/filter/key/") ?
>'+paymode,
data:"key="+paymode,
dataType:'json',
success:function(data){
$("#viewjcexpense").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
<select name="mode" id="mode" >
<option value="BANK CREDIT">CREDIT</option>
<option value="NEFT">NEFT</option>
</select>
is your onchange event working ?
let's check with
$("#mode").change(function(){
alert(1);
});
if when u selected an option would be show the alert that's mean ur event working ,
now if that's working fine let's try to playing with ajax and do little recode, here i used post method
[ VIEW ]
$("#mode").change(function(){
$.ajax({
type : 'POST',
url : '<?=base_url(); ?>JcMeetingExpense/filter/',
data : { key : $("#mode").val() },
success : function(data){
console.log(data);//let's check on console what's response is
}
});
})
[CONTROLLER]
public function filter()
{
$this->load->helper('url');
$this->load->model('JcMeetingExpense_model');
$dataKey = $this->JcMeetingExpense_model->get_data_by_key();
echo json_encode($datadataKey);
}
[MODEL]
public function get_data_by_key()
{
//do post here let's say
$key = $this->input->post("key");
// i looked your query is vulnerable to SQL Injection
/* $sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array(); */
//so let's use query builder
$this->db->select("*");
$this->db->from("employee");
$this->db->where("modeofpay",$key);
$q = $this->db->get();
return $q->result_array();
}
now check response in console
<script type="text/javascript">
$("body").on('change','#mode',function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("JcMeetingExpense/filter/key/") ?
>'+paymode,
data:"key="+paymode,
dataType:'json',
success:function(data){
$("#viewjcexpense").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
try this script instead of your previous script
i have changed $("#mode").change(function(){}); with $("body").on('change','#mode',function(){});

How to get the values from multiple form in one post request using laravel?

Ajax:
<script type="text/javascript">
$(document).ready(function () {
$('#finalSubmit').click(function() {
var form1 = $('#priceform').serialize();
var form2 = $('#formdescription').serialize();
var form3 = $('#additionaldescription').serialize();
//var form4 = new FormData($("#imagesform").get(0));
//alert(form4);
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content') }
});
$.ajax({
url :"{{url('/dbvalue')}}",
type: 'POST',
data: {form1: form1, form2: form2,form3: form3},
dataType:'json',
success:function(data){
alert(data);
}
});
});
});
</script>
This is my ajax code.Here I'm passing the values of four forms
Controller:
public function finalSubmit(Request $request)
{
var_dump($_POST);
$var1 = $this->addPriceDetails1($request->form1);
$var2 = $this->addProductDetails1($request->form2);
$var3 = $this->addAdditionalInformation1($request->form3);
//$var4 = $this->addImages($imagesform);//you dont't have
$imagesform
return response()->json(["response"=>"success"]);
}
Eg. for function:
public function addPriceDetails1($request)
{
$priceInfo = new priceInfo ;
$priceInfo->id=$this->getpriceDetailsId();
$priceInfo->SKUID=$request->input('skuid');
echo($priceInfo->id);
//return $request->all();
}
Also here when I'm trying to echo the values of $priceInfo->Id it echoes '0'.I don't know why
With this I'm getting FatalErrorException..call to member function input() on string
var_dump($_POST) gives me an array of forms values.
UPdate:
public function getpriceDetailsId()
{
$id = mt_rand(1000000, 9999999);
$id="PD".$id;
$count=priceInfo::select('id')->where('id',$id)->count();
if($count==0)
{
return $id;
}
else
{
$this->getpriceDetailsId();
}
}
here is my function for getpriceDetailsId().
You get that error because your input query when you access as object when it is string, you can convert your query string to an array to access like so.
public function addPriceDetails1($request)
{
parse_str($request, $input);
$priceInfo = new priceInfo ;
$priceInfo->id = $this->getpriceDetailsId();
$priceInfo->SKUID = $input['skuid'];
echo($priceInfo->id);
}
Hope this help

Trying to populate worker ID using Compay Name but only the first worker in that company is displayed in dropdown

This is the view page code in code Igniter.
I am able to populated the second drop down(worker Id) but the problem is, only first data is being fetched. As it has more than 50 worker, only 1 worker id is being fetched.
$(document).ready(function() {
$('#name_of').change(function() {
var Worker_id = $('#name_of').val();
$.ajax({
type:'POST',
data:{data:Worker_id},
dataType:'text',
url:"<?php echo base_url(); ?>supply_chain/get_filtered_names_for_time_card",
success:function(result) {
result = JSON.parse(result);
$('#Worker').empty();
for(i in result) {
$('#Worker').append("<option value='"+result[i]['Worker_id']+"'>"+result[i]['Worker_id']+" "+result[i]['Worker_name']+"</option>")
}
}
});
});
});
This is the Controller function for above View through which I am trying to get all workers related to that required company name.
public function get_filtered_names_for_time_card() {
$id = $this->input->post('data');
$companyName = $this->supply_model->get_all_names_for_time_card();
for($i = 0;$i < sizeof($companyName);$i++){
if($companyName[$i]['company_name'] == $id){
$data['companyNameOptions'] = [$companyName[$i]];
break;
}
}
echo json_encode($data['companyNameOptions']);
}
It would be a much better idea to make the query select only the row you want but your problem with the code you have written is you over writing the data each time round your loop
Also once you find a company_name you want you terminate the for loop with a break so you will only ever add one to the resulting $data array
public function get_filtered_names_for_time_card()
{
$id = $this->input->post('data');
$companyName = $this->supply_model->get_all_names_for_time_card();
for($i = 0;$i < sizeof($companyName);$i++){
if($companyName[$i]['company_name'] == $id){
$data['companyNameOptions'][] = $companyName[$i];
// note here ^^
//break;
}
}
echo json_encode($data['companyNameOptions']);
}
Also the $data array does not need to have a sub array so above code can be written more simply and clearly as
public function get_filtered_names_for_time_card()
{
$id = $this->input->post('data');
$companyName = $this->supply_model->get_all_names_for_time_card();
for($i = 0;$i < sizeof($companyName);$i++){
if($companyName[$i]['company_name'] == $id){
$data[] = $companyName[$i];
}
}
echo json_encode($data);
}
And in your javascript, if you are returning JSON then tell the ajax call that you are doing that and you can forget about the JSON.parse()
$(document).ready(function(){
$('#name_of').change(function(){
var Worker_id = $('#name_of').val();
$.ajax({
type:'POST',
data:{data:Worker_id},
//dataType:'text',
dataType:'json',
url:"<?php echo base_url(); ?>supply_chain/get_filtered_names_for_time_card",
success:function(result)
{
//result = JSON.parse(result);
$('#Worker').empty();
for(i in result){
$('#Worker').append("<option value='"+result[i]['Worker_id']+"'>"+result[i]['Worker_id']+" "+result[i]['Worker_name']+"</option>")
}
}
});
});
});

jQuery JSON not passing data to Ci properly

The script below works as far as i can tell:
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#add').bind('keypress', function(e) {
if(e.keyCode == 13){
var add = $("#add").val();
$.ajax({
type: "POST",
dataType: "JSON",
url: "<?php echo site_url("home/jsonAddData"); ?>",
data: add,
json: {title_posted: true},
success: function(data){
if(data.title_posted == true) { // true means data was successfully posted.
$("#success").append("Success").fadeIn(400);
} else if(data.title_posted == false) { // false means data failed to post.
$("#success").append('Failure').fadeIn(400);
}
}
});
}
});
});
</script>
The problem I'm experiencing with the code below is that the mysql insetion query just wont work. It creates the row in the table and auto-increments but for some odd reason it wont pass the 'var add' in the Javascript above to the Ci script below and perform an insertion in the db. Any thoughts or ideas?
<?php
class home extends CI_Controller {
function __construct() {
parent::__construct();
}
function index() {
$data = array();
$data['lists'] = $this->displayList();
$this->load->view('home', $data);
}
function displayList() {
$str = '';
$query = $this->db->query("SELECT * FROM data");
foreach ($query->result() as $row) {
$b = '<input name="completed" type="checkbox" />';
$a = $row->title . "<br>";
$str .= $b.$a;
}
return $str;
}
function jsonAddData() {
if($this->input->is_ajax_request()) {
$title = $this->input->post('title');
$query = $this->db->query("INSERT INTO data (title) VALUES ('$title')");
header('Content-type:application/json');
if($query) echo json_encode(array('title_posted' => true));
else echo json_encode(array('title_posted' => false));
}
}
}
?>
In
$.ajax({
...
data: {title: add}
Not just a string

Categories