I am trying to implement a chart from database, but I'm having a few problems...
I have a Database with 2 rows: Date, Pcr
My files .php:
Data.php
$query = "SELECT * FROM `table1` ORDER BY Date LIMIT 0 , 100";
$result = mysql_query($query) or die("SQL Error 1: " . mysql_error());
$dates=array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$dates[] = $row['Date'];
$dates[] = $row['Pcr'];
}
echo json_encode($dates);
I get the array:
["2015-06-14","0.77","2015-06-20","0.79","2015-09-24","0.88","2015-10-26","0.8","2015-10-30","0.7"]
I would like to get a dynamic chart from this array, but I don't know how to do that...
I have this static file:
chart.php
<div class="resultados"><canvas id="grafico"></canvas></div>
<script>
$(document).ready(function(){
$.ajax({
type:'POST',
url:'data.php',
success:function(data){
var valores = eval(data);
var date1 = valores[0];
var pcr1 = valores[1];
var date2 = valores[2];
var pcr2 = valores[3];
var date3 = valores[4];
var pcr3 = valores[5];
var date4 = valores[6];
var pcr4 = valores[7];
var Datos = {
labels : [date1,date2,date3,date4],
datasets : [
{
fillColor : 'rgba(255,0,0,0.1)',
strokeColor :'rgba(255,0,0,100)',
pointColor : 'rgba(255,0,0,100)',
pointStrokeColor:"#e32636",
pointHighlightFill:"#bbf",
pointHighlightStroke:"rgba(255,0,0,255)",
data : [pcr1,pcr2,pcr3,pcr4]
}
]
}
var contexto = document.getElementById('grafico').getContext('2d');
window.Barra = new Chart(contexto).Line(Datos, { responsive : true });
}
});
return false;
}
)
</script>
Could someone help me to find what I have to put in Data:[]?
Thank you very much
php:
$dates=array();
$pcrs=array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$dates[] = $row['Date'];
$pcrs[] = $row['Pcr'];
}
$data = ["dates"=>$dates,"pcrs"=>$pcrs];
echo json_encode($data);
js:
$(document).ready(function(){
$.ajax({
type:'GET',
url:'data.php',
success:function(data){
var Datos = {
labels : data.dates,
datasets : [
{
fillColor : 'rgba(255,0,0,0.1)',
strokeColor :'rgba(255,0,0,100)',
pointColor : 'rgba(255,0,0,100)',
pointStrokeColor:"#e32636",
pointHighlightFill:"#bbf",
pointHighlightStroke:"rgba(255,0,0,255)",
data : data.pcrs
}
]
}
var contexto = document.getElementById('grafico').getContext('2d');
var chrt = new Chart(contexto).Line(Datos, { responsive : true });
}
});
return false;
}
)
Related
i have problem with the post value in my form
i show you my code and see if you can help me
<script src="//netsh.pp.ua/upwork-demo/1/js/typeahead.js"></script>
<script>
$(document).ready(function() {
$('#ville').on('change', function(){
var id_ville = this.value;
$.ajax({
type: "post",
url: "lycee.php",
data: 'id_ville=' + id_ville,
success: function(result){
$("#lycee").html(result);
}
});
$('input.lycee').typeahead({
name: 'lycee',
remote: 'lycee.php?query=%QUERY'
});
});
})
</script>
<script >
and this is my php part code
$id_ville = mysql_real_escape_string($_POST['id_ville']);
if($id_ville!='') {
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = $conn->query ("SELECT nom_lycee
FROM ville_lycee
INNER JOIN ville ON ville.id_ville = ville_lycee.id_ville
INNER JOIN lycee ON lycee.id_lycee = ville_lycee.id_lycee
WHERE ville.id_ville = '" . $id_ville . "'
AND lycee.nom_lycee LIKE '%{$query}%' ");
$options = "<label value=''></label>";
$array = array();
while ($row = $sql->fetch_assoc()) {
$array[] = array (
'label' => $row['nom_lycee'],
'value' => $row['nom_lycee'],
);
}
echo json_encode ($array);
}
}
the problem is that i need the id_ville value first and then the Query to filtre
I am working on dynamic j query data table where i want to show data from 3 tables.
It should be expandable.I am done to achieve with 1 table. but after joins another 2 tables its not working.
I am attaching my tables format and all pictures how should be my data look.
I have total 4 tables. employee_master,uk_slip,germany_slip,poland_slip.
each user have his pay_slips for each country for each month.
For eg. XYZ is employee.
he will get his 3 salary_slips for 2018-FEBRUARY.I want to show one datatable where first user will see his name then on expand datatable he will get in below format his all slips.
My current code is is showing only data from uk_slip. after UK another tables data should be display.
My model:
public function get_all_payslips()
{
$empid = $this->session->userdata('EMPLOYEE_ID');
$orgid = $this->session->userdata('CURRENT_ORG_ID');
$where = "EMPLOYEE_ID ='".$empid."' ";
$response = array();
$queryString = "SELECT
em.EMPLOYEE_ID,
em.EMPLOYEE_NAME
FROM
uk_slip assd,
employee_master em
WHERE
em.".$where."
GROUP BY em.EMPLOYEE_ID
order by em.EMPLOYEE_NAME asc";
$query = $this->db->query($queryString);
foreach ($query->result() as $data)
{
$result = array();
$result['EMPLOYEE_NAME'] = $data-> EMPLOYEE_NAME;
$queryString = "SELECT
mo.months,
MONTH((assd.pay_period)) as monthss,
YEAR((assd.pay_period)) as PAY_YEAR,
GROUP_CONCAT(DISTINCT(assd.id)) as action,
CONCAT(assd.ORG_ID,',',germany.ORG_ID,',',poland.ORG_ID) as org
FROM
uk_new_salary_slip assd,
employee_master em,
months mo,
germany_slip germany,
poland_slip poland
WHERE
assd.emp_id = ". $data->EMPLOYEE_ID ."
AND mo.id = MONTH((assd.pay_period))
GROUP BY monthss,PAY_YEAR
order by PAY_YEAR desc";
$query1 = $this->db->query($queryString);
$children = array();
foreach ($query1->result() as $data1)
{
$yearArray = array();
$yearArray['month'] = $data1->months;
$yearArray['year'] = $data1->PAY_YEAR;
$yearArray['org'] = $data1->org;
$yearArray['action'] = $data1->action;
array_push($children, $yearArray);
}
$result['children'] = $children;
array_push($response, $result);
}
return $response;
}
My View with jquery datatable:
$(document).ready(function()
{
var table = null;
$.ajax({
url:"<?php echo base_url('responsible/get_all_payslips'); ?>",
datatype:'json',
success: function(response)
{
var response1 = $.parseJSON(response);
console.log(JSON.stringify(response1['pay_slips']));
var data = response1['pay_slips'];
table = $('.datatables').DataTable({
columns : [
{
className : 'details-control',
defaultContent : '',
data : null,
orderable : false
},
{data : 'EMPLOYEE_NAME'},
],
data : data,
pagingType : 'full_numbers',
});
}
});
function format(data)
{
return '<div class="details-container">'+
'<table class="details-table table-bordered">'+
'<thead>'+
'<tr>'+
'<th>Year</th>'+
'<th>Month</th>'+
'<th>PDF</th>'+
'</tr>'+
'</thead>'+
'<tbody>'+
'<tr>'+
'<td>'+data.PAY_YEAR+'</td>'+
'<td>'+data.monthss+'</td>'+
'<td>'+'<a class="btn btn-success" href="data.action">'+data.action+'</a>'+'</td>'+
'</tr>'+
'<tr>'+
'<td>'+data.PAY_YEAR+'</td>'+
'<td>'+data.monthss+'</td>'+
'<td>'+'<a class="btn btn-success" href="data.action">'+data.action+'</a>'+'</td>'+
'</tr>'+
+'</tbody>'+
'</table>'+
'</div>';
};
$('.datatables tbody').on('click', 'td.details-control', function ()
{
var tr = $(this).closest('tr');
var row = table.row( tr );
console.log(row.data()['children']);
var childrenArray = row.data()['children'];
var check = '<div class="details-container">'+
'<table class="details-table table-bordered">'+
'<thead>'+
'<tr>'+
'<th>Year</th>'+
'<th>Month</th>'+
'<th>PDF</th>'+
'</tr>'+
'</thead>'+
'<tbody>';
for(var i=0;i<childrenArray.length;i++)
{
check +='<tr>'+
'<td>'+childrenArray[i].year+'</td>'+
'<td>'+childrenArray[i].month+'</td>';
var orgid = childrenArray[i].org.split(",");
var action = childrenArray[i].action.split(",");
var obj = {};
for (var k = 0; k < orgid.length; k++)
{
obj[orgid[k]] = action[k];
}
var arrayData = sortObject(action);
check +='<td>';
for(var j=0;j<arrayData.length;j++)
{
var country = "";
var color = "";
if(arrayData[j].key=="40")
{
country = "1";
color = "INDIANRED";
}
else if(arrayData[j].key=="41")
{
country = "2";
color = "LIGHTPINK";
}
else if(arrayData[j].key=="47")
{
country = "3";
color = "LIGHTSALMON";
}
else
{
country = "UK";
color = "DARKKHAKI";
}
check+='<a class="btn btn-success" style="background-color : ' + color + ';" href="<?php echo base_url()?>responsible/uk_pdf/'+arrayData[j].value+'">'+country+
'</a>|';
}
check +='</td></tr>';
}
check += '</tbody>'+
'</table>'+
'</div>';
if (row.child.isShown())
{
tr.next('tr').removeClass('details-row');
row.child.hide();
tr.removeClass('shown');
}
else
{
row.child(check).show();
tr.next('tr').addClass('details-row');
tr.addClass('shown');
}
});
});
function sortObject(obj)
{
var arr = [];
console.log(arr);
for (var prop in obj)
{
if (obj.hasOwnProperty(prop))
{
arr.push({
'key': prop,
'value': obj[prop]
});
}
}
arr.sort(function(a, b) { return a.value - b.value; });
return arr;
}
In all 3 slip_tables emp_id is common. then in each table having ORG_ID column. for UK having ORG_ID = 40, for GERMANY = 57, for POLAND = 47. In uk_slip having column pay_period for getting MONTH and YEAR with mysql functions MONTH and YEAR. and in germany and poland having pay_from to get the same.
So I have a PHP script where I ask a simple query and then I put it in an array.
<?php
$query = mysql_query('SELECT ATX12V FROM results');
$resultSet = array();
while($row = mysql_fetch_array($query)){
$resultSet['ATX12V'] = $row['ATX12V'];
$data[] = $resultSet;
}
print json_encode($data);
?>
The outcome of print json_encode($data) is:
[{"ATX12V":"10"},{"ATX12V":"65"},{"ATX12V":"64"},{"ATX12V":"96"}]
Below I have a javascript code and my question is how do I add $data to the data[]??
<script>
var buyerData = {
labels : ["January","February","March","April","May","June", "July", "August"],
datasets : [
{
fillColor : "#9DB86D",
strokeColor : "#ACC26D",
pointColor : "#9DB86D",
pointStrokeColor : "#9DB86D",
data : []
}
]
}
</script>
What about simple:
data : <?php echo json_encode($data); ?>
you can use ajax like :
(home.html):
<script type="text/javascript">
window.onload = function() {
$.ajax({
type: "POST",
url: "request.php",
dataType: "json",
success: function (data) {
alert(data[0].ATX12V);
}
});
}
</script>
<script type="text/javascript" src="js/jquery.js"></script>
and server side (request.php) :
<?php
$query = mysql_query('SELECT ATX12V FROM results');
$resultSet = array();
while($row = mysql_fetch_array($query)){
$resultSet['ATX12V'] = $row['ATX12V'];
$data[] = $resultSet;
}
print json_encode($data);
?>
note: Add jquery.js in your project
How can I pass data from a php of then rows back to ajax ?
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$result = mysql_query($query);
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[]=$rec['pic_location'];
$name[]=$rec['name'];
$age[]=$rec['age'];
$gender[]=$rec['gender'];
}
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Ajax
$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");
$.ajax({
url: "viewnew.php",
dataType: "json",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first image url: " + arr[0][0] + ", second image url: " + arr[0][1]); // This code isnt working
alert("first image Name: " + arr[1][0] + ", second image name: " + arr[1][1]);
$(".theImage").attr("src", arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
});
});
</script>
My question is how can I display the values here ? The Alert message is giving me "Undefined" ?
You can do something along these lines.
PHP
$query = 'SELECT * FROM picture order by rand() LIMIT 10';
$res = mysql_query($query);
$pictures = array();
while ($row = mysql_fetch_array($res)) {
$picture = array(
"pic_location" => $row['pic_location'],
"name" => $row['name'],
"age" => $row['age'],
"gender" => $row['gender']
);
$pictures[] = $picture;
}
echo json_encode($pictures);
JS
...
$.ajax({
...
dataType: "json",
...
success: function(pictures){
$.each(pictures, function(idx, picture){
// picture.pic_location
// picture.name
// picture.age
// picture.gender
});
}
});
...
You can't put multiple echo statements for the AJAX response:
echo json_encode($url);
echo json_encode($name);
echo json_encode($age);
echo json_encode($gender);
Join your arrays and send a single response:
$arr = $url + $name + $age + $gender;
echo json_encode($arr);
You can easily do this using a single Array:
$pics = array();
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$pics[$rec['id']]['url'] = $rec['pic_location'];
$pics[$rec['id']]['name']=$rec['name'];
$pics[$rec['id']]['age']=$rec['age'];
$pics[$rec['id']]['gender']=$rec['gender'];
}
echo json_encode($pics);
Just doing a small project relating to google maps.
Basically I have coordinates in a database that I want to retrieve using ajax, and update the map without the need to refresh the page.
php part:-
$deviceID = $_POST['deviceID'];
$sqlLocation = "SELECT * FROM Location WHERE DeviceID = '".$deviceID."' AND Type ='network'";
$sqlResult = mysql_query($sqlLocation);
while($row = mysql_fetch_assoc($sqlResult))
{
$response["uid"] = $row["DeviceID"];
$response["deviceInfo"]["Longitude"] = $row["Longitude"];
$response["deviceInfo"]["Latitude"] = $row["Latitude"];
$response["deviceInfo"]["Type"] = $row["Type"];
$response["deviceInfo"]["latlontime"] = $row["latlontime"];
echo json_encode($response);
}
the format of the multiple json result :-
{"uid":"*deviceID here*","deviceInfo":
{"Longitude":"x.xxxxxxx","Latitude":"x.xxxxxxx","Type":"network","latlontime":"2012-05-05 18:55:12"}
}
{"uid":"*deviceID here*","deviceInfo":
{"Longitude":"y.yyyyyyyyy","Latitude":"y.yyyyyyyyy","Type":"network","latlontime":"2012-05-05 18:55:56"}
}
javaScript part with some pseudo code sorry !
var map;
var count =0;
function initialize(DeviceID)
{
if(DeviceID!=null)
{
$.ajax({
type:"POST",
dataType:"json",
data:{deviceID: DeviceID},
url: "json_coords.php",
contentType: "application/json; charset=utf-8",
success: function(data)
{
*****problem used be here******
var len = data.length;
for( var i = 0; i<len; i++)
{
var json_row = data[i];
var latitude = json_row.deviceInfo.Latitude;
var longitude = json_row.deviceInfo.Longitude;
var title = "pos: "+i+json_row.deviceInfo.Type + " "
+json_row.deviceInfo.latlontime ;
//alert_test(latitude,student.Longitude);
setMarker(latitude,longitude,title);
*********************************************************************************
}
}
});
}
else
{
// do nothing
}
var latloncenter = new google.maps.LatLng(51,-1.4469157);
var myOptions =
{
zoom: 4,
center: latloncenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function setMarker(lat,lon,titletxt)
{
var latlongMarker = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker
(
{
position: latlongMarker,
map: map,
title:titletxt
}
);
}
the initialize function will be called after pressing a certain divs on the website:-
$('#leftcolumn>a').click(function()
{
var deviceID = $(this).attr("name");
//alert(deviceID);
initialize(deviceID)
});
I would really appreciated if you can help me out
Thank you :)
* the original problem was around how to retrieve data from a php page with json results**
the Ajax function of jQuery (in JSON mode) expected a unique json object, you ara sending 2, the format is invalid.
You can do:
$response = array();
while($row = mysql_fetch_assoc($sqlResult))
{
$response[] = (object) array(
'uid' => $row["DeviceID"],
'deviceInfo' => (object) array (
'Longitude' => $row["Longitude"],
'Latitude' => $row["Latitude"],
'Type' => $row["Type"],
'latlontime' => $row["latlontime"]
)
);
}
echo json_encode($response);
And onsuccess callback:
success: function(data) {
$.each(data, function (device) {
var title = device.Type + ' ' + device.latlontime;
setmarker( device.Longitude ,device.Latitude , title);
});
}
<html>
<head>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false®ion=GB"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</head>
<body onload="initialize();">
<div id="map_canvas" style="height:300px;width:500px"></div>
Load markers
<script type="text/javascript">
var map;
var count =0;
function initialize()
{
var latloncenter = new google.maps.LatLng(51,-1.4469157);
var myOptions =
{
zoom: 4,
center: latloncenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
function loaddata(DeviceID)
{
if(DeviceID!=null)
{
$.ajax({
type: "POST",
dataType: "json",
data:{deviceID: DeviceID },
url: 'mapdata.php',
success: function(data)
{
$.each(data,function(index,value) {
console.log(value);
/// I know there is no such thing as data.jsonGetvalueByID just trying to explain what I want to do
var longitude = value.deviceInfo.Longitude;
var latitude = value.deviceInfo.Latitude;
var type = value.deviceInfo.Type;
var time = value.deviceInfo.latlontime;
var title = type + " " +time;
//calling function to add map marker
createmarker(longitude, latitude, title);
});
}
});
}
}
function createmarker(lat,lon,titletxt)
{
var latlongMarker = new google.maps.LatLng(lat,lon);
var marker = new google.maps.Marker
(
{
position: latlongMarker,
map: map,
title:titletxt
}
);
return marker;
}
</script>
</body>
</html>
// my ajax file that just fakes the data needed, so replace with your database code.
<?php
$response = array();
$rows = array();
$rows[] = array("DeviceID"=>1,"Type"=>"Network","Longitude"=>"51.4343","Latitude"=>"-2.344","latlontime"=>date("Y-m-d H:i:s"));
$rows[] = array("DeviceID"=>2,"Type"=>"Network","Longitude"=>"55.4343","Latitude"=>"-2.644","latlontime"=>date("Y-m-d H:i:s"));
foreach ($rows as $row)
{
$data["uid"] = $row["DeviceID"];
$data["deviceInfo"]["Longitude"] = $row["Longitude"];
$data["deviceInfo"]["Latitude"] = $row["Latitude"];
$data["deviceInfo"]["Type"] = $row["Type"];
$data["deviceInfo"]["latlontime"] = $row["latlontime"];
$response[] = $data;
}
echo json_encode($response);
?>