how to group the chart - mysql

i want to group this chart like " gender 1" is men and "gender 2" is women, but when i try to code the chart it's difficult to differentiate them.
here is my code
//data.php
<?php
//setting header to json
header('Content-Type: application/json');
//database
define('DB_HOST', '127.0.0.1');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'dbintegrasi');
//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);
if(!$mysqli){
die("Connection failed: " . $mysqli->error);
}
//query to get data from the table
$query = sprintf("SELECT JenisKelaminID, COUNT(JenisKelaminID) as jumlah FROM tahunmasukmagister GROUP BY JenisKelaminID");
//execute query
$result = $mysqli->query($query);
//loop through the returned data
$data = array();
foreach ($result as $row){
$data[] = $row;
}
//freee memory associated with result
$result->close();
//close connection
$mysqli->close();
//new print the data
print json_encode($data);
//app.js
$(document).ready(function(){
$.ajax({
url: "http://localhost/chartjs/data.php",
method: "GET",
success: function(data) {
console.log(data);
var Gender = [];
var jumlah = [];
for(var i in data){
Gender.push("Gender " + data[i].JenisKelaminID);
jumlah.push(data[i].jumlah);
}
var chartdata = {
labels: Gender,
datasets: [
{
label : 'Gender',
backgroundColor: 'rgba(250, 300, 100, 0.75)',
borderColor: 'rgba(200, 200, 200, 0.75)',
hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
hoverBorderColor: 'rgba(200, 200, 200, 1)',
data: jumlah
}
]
};
var ctx = $("#mycanvas");
var barGraph = new Chart(ctx, {
type: 'bar',
data: chartdata
});
},
error: function(data) {
console.log(data);
}
});
});
please help me to solve this, thankyou

In you app.js file on line number 10 :
Gender.push("Gender " + data[i].JenisKelaminID);
you can set an if condition instead of it Like
if(data[i].JenisKelaminID == 1){
Gender.push("Men");
} else if(data[i].JenisKelaminID == 2){
Gender.push("Women");
} else {
Gender.push("Other");
}
In there the chart name is defined, hope it will help your work.

Related

Update the data in datatable instead of reload whole page in codeigneator

When I insert or update the data using modal form of bootstrap and ajax It's reload the whole page. Instead of reload whole page only refresh the data table.
This is My Script of ajax:-
<script>
$(document).ready(function(){
$('#tbl_member').dataTable({
"iDisplayLength": 10,
"bAutoWidth": false,
"aoColumnDefs": [
{"bSortable": false, "aTargets": [0,2]}
]
});
});
</script>
<script type="text/javascript">
$('.editTech').on('click',function()
{
var id = $(this).data('id');
$.ajax({
url : "<?php echo base_url(); ?>Technology/loadEditTech",
type : "POST",
data:{"id":id},
success : function(data)
{
$('#techModal .modal-content').html(data);
techValidateEdit();
$('#techModal').modal('show');
},
error: function()
{
alert("failure");
}
});
});
function techValidateEdit()
{
$('#frmTech').validate({
rules:{},
submitHandler:function()
{
$.ajax({
url : "<?php echo base_url(); ?>Technology/manage_technology",
type : "POST",
data : $('#frmTech').serialize(),
success : function(data)
{
$('#techModal').modal('hide');
window.location.reload();
},
error: function()
{
alert('error');
}
});
}
});
}
</script>
Here The scenario is when i click on add button open the modal form and add some data after click on save button from modal form it's reload the page. But I want reload only data table instead of reload whole page.
I am using version 1.9.4 of datatable.
Please try this tutorial Here is your answer: http://w3code.in/2015/09/how-to-insert-and-view-data-without-refreshing-page-using-ajax-and-jquery-in-codeigniter/
Because it is not possible to write down the full code here. Thanks
I actually have a very nice piece of code to do this exact thing too!
I generate my datatable with some queries from CI which get each column name for me so it will auto generate the headers for me, my Jquery looks like :
$("td").click(function(e){
var $oldvalue = $(this);
$oldvalue = $oldvalue.html();
var $id =$(this).parent().data('id');
$('td[contenteditable]').keydown(function(e) {
// trap the return key being pressed
if (e.keyCode === 13) {
e.preventDefault();
var $value = $(this);
var $field = $("table thead tr th").eq($value.index());
$valuenew = $value.html();
$field = $field.html();
$.post( "/admin/database/ajax/edit", { id: $id,newvalue: $valuenew, field: $field , table : "users"} );
}
});
});
My controller handles the request as follow:
function ajaxEdit(){
$array = array($this->input->post("field") => $this->input->post("newvalue"));
$this->general_model->updateRow($this->input->post("table"), 'id', $this->input->post("id"), $array);
}
My model looks as follow:
public function updateRow($table, $field, $id, $array = false){
if($array != false){
$array = $array;
} else {
$array = $this->cleanPostArray(); // Let the POST be cleaned / scanned
}
$this->db->where($field, $id);
$this->db->update($table, $array);
return 1; // 1 = success
}
public function cleanPostArray(){
$POSTarray = $this->input->post();
$array = array();
foreach($POSTarray as $key => $val):
if($key == "password"){
// Value needs to be salted / hashed!
if($val != ""){
$val = YourEncryptionForPW;
$array[$key] = $val;
}
}else {
$array[$key] = $val;
}
endforeach;
return $array;
}

PHP MySQL Data To AngularJS

I am using this code to pull data from a MySQL.
$.ajax({
url: 'api.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var icon = data[1];
var english = data[2];
var british = data[3];
$('#output').html("<b>id: </b>"+id+"<b> icon: </b>"+icon+"<b> english: </b>"+english+"<b> british: </b>"+british); //Set output element html
}
And it outputs this correctly but my questions is how would put this data into the below.
$scope.items = [
{
english: '<First Row english>',
british: '<First Row british>',
image: '<First Row icon>'
},
{
english: '<Second Row english>',
british: '<Second Row british>',
image: '<Second Row icon>'
}
//So on and so forth for all the records in the DB.
]
This is from api.php not sure if this needs to be returned a certain way?
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
echo $json_response = json_encode($arr);
?>
<?php
require_once 'db.php'; // The mysql database connection script
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$query=mysql_query("SELECT * FROM $tableName") or die(mysql_error());
$arr[];
while($obj = mysql_fetch_object($query)) {
array_push($arr, $obj);
}
echo $json_response = json_encode($arr);
?>
JS
$http.get('api.php').success(function(data) {
$scope.items = data;
});

How to use subgrid with Jqgrid and JSON?

I'm a jqrid newbie. My problem is how to make it work using subgrid? This is the js file :
var url = $.url(window.location.href.replace("#",""));
var page = url.param("page");
var sortname = url.param("sortname");
var sortorder = url.param("sortorder");
jQuery("#list2").jqGrid({
url:'/taskuri/json/',
datatype: "json",
colNames:['Pri','Proiect','','Task', '', 'Responsabil','Alocator', 'Alocat', 'Deadline','Estimat','Lucrat',''],
colModel:[
{name:'priority',index:'priority', width:'3%', editable: true, editoptions:{size:"1",maxlength:"1"}},
{name:'project',index:'project', width:'7%'},
{name:'finished',index:'finished', width:'2%'},
{name:'section',index:'section', width:'38%'},
{name:'projectid',index:'projectid',hidden:true},
{name:'user',index:'user', width:'7%', editable: true,edittype:'select',editoptions:{value:getUsers }},
{name:'assignerid',index:'assignerid', width:'7%'},
{name:'created',index:'created', width:'6%', editable:true},
{name:'deadline',index:'deadline', width:'6%', editable:true},
{name:'estimated',index:'estimated', width:'4%', editable:true, align:'right'},
{name:'worked',index:'worked', width:'5%',align:'right', align:'right'},
{name:'remove',index:'remove', width:'3%', sortable:false}
],
rowNum:100,
sortname: (sortname != null) ? sortname : 'taskid',
viewrecords: true,
sortorder: (sortorder!=null) ? sortorder : "desc",
caption:"",
autowidth: true,
shrinkToFit: true,
height:'auto',
//width: '100%',
scroll:false,
scrollOffset:0,
//height: '100%',
altRows: true,
altClass: '',
page: (page!=null)? page: 1,
footerrow : true,
userDataOnFooter: true,
subGrid : true,
subGridUrl: '/taskuri/subGrid/',
subGridModel: [{ name : ['Test1','Test2'],width : [55,200,80,80,80] } ],
loadComplete:function(request){
$('#totalRows').html(request.total + " rezultate");
$("[aria-describedby='list2_section']", this).contextMenu('myMenu1',{
onContextMenu: function(e) {
var rowId = $(e.target).closest("tr.jqgrow").attr("id");
var projectName = $('#list2').jqGrid('getCell',rowId,'project');
var taskName = $('#list2').jqGrid('getCell',rowId,'section');
var regex = /<a.+>(.+)\<\/a>/;
var result = taskName.match(regex)[1];
//if($(e.target).closest('a').attr("class"))
//{
$("#addSubTask").click(function(){
$('#proiectName').val(projectName);
$('#taskName').val(result);
$("#adsubtaskdialog").dialog({show:"slow", title: "Adaugare SubTask",
resizable: true, width:337
});
});
//$("#addSubTask").html('<a href="/timp/editSubtask/?action=start&projectName='+projectName+'&taskName='+result+'" class="addTime" >Adauga SubTask</a>');
$("#send").html('<a onclick="send_email('+rowId+')">Trimite email de reamintire</a>');
return true;
//}
//else
// return false;
}
});
$("#paging").html(request.userdata.pager);
$(".numb").click(function() {
$("#list2").trigger("reloadGrid", [{page:$(this).text()}]);
});
doPagination();
showConfirm();
formatUrl();
setBackUrl();
$("#empty").hide();
if(request.total == 0)
$("#empty").show();
registerOverlay();
//footer row hack
$(".ui-jqgrid-sdiv").width('auto');
$(".ui-jqgrid-ftable").css("margin-top",0);
},
..........
where taskuri/subGrid/ (taskuri is a controller) and subGrid(is a function). Im using Codeigniter. The function has the following code :
$this->load->library('JSON');
$examp = $_GET["q"]; //query number
$id = $_GET['id']; // connect to the database
$query = "SELECT taskid,name, deadline
FROM tasks
WHERE taskid='8516'
ORDER BY taskid";
$result = mysql_query($query);
$i =0 ;
while($row = mysql_fetch_array($result)) {
$response->rows[$i]=$row;
$i++;
}
echo json_encode($response);
Im totally confused. Can anyone help me with this ? This is a picture how does it look like:

comparing json submitted array and sql returned array and printing difference in text file

I am submitting a javascript array to another php page via ajax which runs a query and returns another array. Then i would like to compare these two arrays and print the difference in a text file. The code give below is creating a text file with no data in it.
Here is the code
$('#tabletomodify').on('change','.street',
function (event)
{
event.preventDefault();
var row=( $(this).closest('tr').prop('rowIndex') );
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
var ideSelected= this.id;
var values = '[';
values+=valueSelected+",";
for ($i=3;$i<row;$i++)
{
var dv="selectcity"+$i;
var dv1=document.getElementById(dv).value;
var sl="street"+$i;
var sl1=document.getElementById(sl).value;
var po="building"+$i;
var po1=document.getElementById(po).value;
var concat=dv1+sl1+po1;
values+=''+concat+',';
}
values = values.substring(0,values.length-1);
values += ']';
$.ajax({
url: "get_buildings.php",
type: 'POST',
data: {data: values} ,
success: function(){
alert("Success!")
}
});
the value sent to the get_buildings.php is
[newyork::roosevelt st,springfieldevergreen terraceno42,quahogspooner streetno43]
Php code get_buildings.php:-
$a1='newyork::roosevelt st';
$sl= explode("::",$a1);
$a=$sl[1];
$connection_buildings= mysqli_connect('localhost', 'xxxx', 'xxxx', 'DETAILS') or die ('Cannot connect to db');
$sql_query_3 = "select buildings from $a";
$result_query_3=mysqli_query($connection_buildings,$sql_query_3) or die ("check it");
$options=array();
while ($row = $result_query_3->fetch_assoc())
{
$name = $row['buildings'];
$val=$a.$sl[0].$name;
array_push($options,$val);
}
$result = array_diff($_POST['data'], $options);
$fp = fopen("textfile.txt", "w");
fwrite($fp, $result);
fclose($fp);
mysqli_close($connection_buildings);

Google Org Chart - Draw a chart from JSON (mysql)

I'm trying to draw an organizational chart (http://goo.gl/wgftfO) from JSON (php - mysql) but it doen'st display well.
Here is my HTML code:
<script type="text/javascript">
google.load('visualization', '1', {packages:['orgchart']});
google.setOnLoadCallback(drawChart);
function json(){
$.ajax({
type: "POST",
url: "function/ver.php",
success: function(datos){
datos = eval(datos);
for (var i=0;i<datos.length;i++){
var id = datos[i].id;
var nombre = datos[i].nombre;
var jefe = datos[i].jefe;
alert(id);
drawChart(id, nombre);
function drawChart(id, nombre) {
//alert("Id: " + id + " | Nombre: " + nombre);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
data.addRows([
[nombre, jefe, id]
]);
var chart = new google.visualization.OrgChart(document.getElementById('contenido'));
chart.draw(data, {allowHtml:true});
}
}
},
error: function(error){
alert(error);
}
});
}
</script>
</head>
<body onLoad="json()">
<div id="contenido"></div>
</body>
JSON result:
[
{
"id":"1",
"nombre":"Andrey",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-G1-icon.png",
"jefe":""
},
{
"id":"2",
"nombre":"Enrique",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-F3-icon.png",
"jefe":"Andrey"
},
{
"id":"3",
"nombre":"Chero",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-E4-icon.png",
"jefe":"Andrey"
},
{
"id":"4",
"nombre":"Ricardo",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-F3-icon.png",
"jefe":"Chero"
},
{
"id":"5",
"nombre":"Jhon",
"paterno":null,
"foto":"http:\/\/icons.iconarchive.com\/icons\/deleket\/face-avatars\/256\/Male-Face-H1-icon.png",
"jefe":"Enrique"
}
]
This displays like:
And, if i remove the alert(id) form the HTML code (in ajax), just shows the last object of the JSON:
How can i fix this?
or, is there any other option to do this chart?
Thank your for answers
The bellow code worked for me
index.html
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript' src='js/jquery.min.js'></script>
<script type='text/javascript'>
google.load('visualization', '1', { packages: ['orgchart'] });
google.setOnLoadCallback(drawChart);
function drawChart() {
$.ajax({
type: "POST",
url: "ajax/organization.php",
success: function(result){
var result = JSON.parse(result);
if ((emp_count = result.length) > 0) {
console.log(result);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addRows(emp_count);
for (i = 0; i < emp_count; i++) {
data.setCell(i, 0, result[i].emp);
data.setCell(i, 1, result[i].manager);
}
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
chart.draw(data, { allowHtml: true });
}
}
});
}
</script>
organization.php
define('DB_SERVER', 'localhost');
define('DB_USERNAME', 'USERNAME');
define('DB_PASSWORD', 'PASSWORD');
define('DB_DATABASE', 'DATABASE_NAME');
$connection = mysql_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD) or die(mysql_error());
$database = mysql_select_db(DB_DATABASE) or die(mysql_error());
$query=mysql_query("select emp, manager from employees") or die(mysql_error());
# Collect the results
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
# JSON-encode the response
$json_response = json_encode($arr);
// # Return the response
echo $json_response;