I have a problem I am able to change my Morris.js Chart to bar graph to line graph the problem is the design of the line graph. Please refer to the two (2) screen shots to see what I meant. When I switch the graph into a line graph the graphical representation of data is messed up. How can I fix this?
Bar Graph
Line Graph
PHP Code I used :
$sql = "SELECT MONTHNAME(date) AS date, SUM(sales) AS sales FROM tblSales WHERE YEAR(date)=YEAR(now()) GROUP BY MONTHNAME(date)";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
$ar[] = array(
'month' => $row['date'],
'sales' => $row['sales']
);
}
ob_clean();
echo json_encode($ar);
AJAX Code I used :
var statement = 1;
$.ajax ({
url:"show_total_overall_sales.php",
data: "statement="+statement,
method: "POST",
success: function(branch_data){
new Morris.Line({
element: 'total-sales',
data: JSON.parse(branch_data),
xkey: 'daily',
ykeys: ['sales'],
labels: ['Total Sales'],
hideHover: 'auto'
});
}
});
Maybe you can try to use parseTime:false
Related
I am looking forward chart like this https://i.stack.imgur.com/a6dAq.png with this code
php + html:
$sql = "SELECT val1 , val2 ,t
FROM DvojeHodnoty
INNER JOIN Pristroje ON DvojeHodnoty.dev_name = Pristroje.dev_name
WHERE t>'$startdate2' AND t< '$enddate2' AND Pristroje.nazev_pristroje='$pristroj' order by val1 asc;";
$result = mysqli_query($connection, $sql);
while ($row = mysqli_fetch_array($result))
{
$t = $t.'"'.date('d.m.y H:i:s', $row['t']/1000).'",';
$hodnota = $hodnota.'"'.$row['val1'].'",';
$hodnota2 = $hodnota2.'"'.$row['val2'].'",';
}
$start = date('d.m.y', $startdate2/1000);
$end = date('d.m.y', $enddate2/1000);
$t = trim($t,",");
$hodnota = trim($hodnota,",");
$hodnota2 = trim($hodnota2,",");
}
<div id="chart-container" style="background: white">
<canvas id="chart"></canvas>
<script>
var ctx =document.getElementById("chart").getContext('2d');
var myChart = new Chart(ctx, {
type:'line',
data: {
labels: [<?PHP echo $hodnota2; ?>],
datasets:
[
{
label: '<?PHP echo $start;?> - <?PHP echo $end; ?> Přístroj: <?PHP echo $pristroj;?> ',
data: [<?PHP echo $hodnota; ?>],
backgroundColor:'transparent',
borderColor:'rgba(255,99,132)',
borderWidth: 3
}]
},
options: {
scales: {
yAxes:[{
scaleLabel: {
display: true,
labelString: 'σ',
fontSize: 20
}
}],
xAxes:[{
scaleLabel: {
display: true,
labelString: 'ε',
fontSize:20
}
}]
}
}
})
</script>
</div>
but so far I got only this https://i.stack.imgur.com/Ri8Ho.png.
I don't know how to create chart with two variables, I tried scatter but so far I am stuck with no ability to create graph with x,y line as values. Is there any easy way to create chart with two variables? If so can you help me/ give me some documentation? (I've seen one scatter chart with fix values, but I am not able to do it with php echo (with values from database) since I need to have variable values since user will choose values depends on chosen date. So far I got only 1 value (y) and two values but with text (numbers counted as text not as value) so chart looks weirdly (0,1,-1 still on same line not like normal graph showned up).
The problem was that data type was VARCHAR and for sorting it I need INT. Problem solved
I have this PHP script to get all patient name from my database:
<?php
error_reporting(E_ALL);
ini_set("display_errors", 1);
require_once('connection.php');
header("Content-type:application/json");
$cid = $_SESSION['clinic_id'];
$res = array();
$getPatients = "SELECT * FROM patient WHERE clinic_id = :cid ORDER BY patient_id DESC";
$execGetPatients = $conn->prepare($getPatients);
$execGetPatients->bindValue(':cid', $cid);
$execGetPatients->execute();
$getPatientsResult = $execGetPatients->fetchAll();
$i = 0;
foreach($getPatientsResult as $result)
{
$res[$i] = $result;
$i++;
}
echo json_encode($res);
?>
And I have a text box where I want to display the patient_name as autocomplete using jquery-ui autocomplete library.
Here is my jQuery script:
$(document).ready(function()
{
$( "#searchTxt" ).autocomplete({
source: "../php/autoComplete.php"
});
})
I can see that if a type a name at the network tab I can see a returned array:
But at the text box I see that the autocomplete are empty like in the following image:
And it is showing 2 white boxes instead of one that of the returned array
This is nice plugin for that kind of results: https://twitter.github.io/typeahead.js/
I think its because the data you have passed, it seems there are multiple columns, you need to specify label and value or it should be simple array (as per your code it should be this kind of data)like
var availableTags = [
"ActionScript",
"COBOL",
"ColdFusion",
];
You can check more about custom field passing
Twitter typeahead.js is the best option to implement this feature.
Please take a look into this to achieve it with PHP, AJAX, and TypeAhead.js
<script>
$(function() {
$("#searchTxt").typeahead({
source: function(query, process) {
var textVal=$("#searchTxt").val();
$.ajax({
url: '/php/autoComplete.php', // Please add full URL here
type: 'POST',
data: 'term=' + textVal,
dataType: 'JSON',
async: true,
success: function(data) {
process(data);
console.log(textVal);
}
});
}
});
});
</script>
link to TypeAhead.js
Let me know if you need any help.
Because you need label and value filed in your json array so your sql would be,
$getPatients = "SELECT *, name as label, id as value FROM patient WHERE clinic_id = :cid ORDER BY patient_id DESC";
I'm using jQuery ajax + MySQLi's prepared statements to get data from my database. The problem is that I don't know how to exactly format the data to use in Bootstrap's typeahead plugin.
This is the relevant code:
PHP:
$stmt = $mysqli->prepare("SELECT GAME_NAME FROM GAMES WHERE GAME_NAME LIKE ?");
$query = "%".$query."%";
$stmt->bind_param('s',$query);
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
if($count > 0) {
$stmt->bind_result($result);
while($stmt->fetch()) {
echo json_encode($result);
}
What I get as AJAX response is all the names as a bunch of text:
'"game 1""game 2""blaablaa""some other game"....'
I think I have to have an array of names and I don't know how to get the stmt result as an array. The example I tried and works is (I use the array allCities as data-source):
<script type="text/javascript">
$(document).ready(function() {
var allCities = ['Baltimore', 'Boston', 'New York', 'Tampa Bay', 'Toronto', 'Chicago', 'Cleveland', 'Detroit', 'Kansas City', 'Minnesota', 'Los Angeles', 'Oakland', 'Seattle', 'Texas'].sort();
$('#city').typeahead({source: allCities, items:5});
});
</script>
Now if I only could get result in the same format as in the example, my problem should be solved, I think. Btw, I'm not sure about the json_encode() I used in the code. That's just something I gave a try. I appreciate any help. Thanks.
UPDATE, Ajax:
function handleSearch() {
var query = $.trim($('#search-field').val());
var itm = getSearchItem();
$.ajax({
type: "POST",
url: "..//functions/handleSearch.php",
dataType: "json",
data: "query="+query+"&itm="+itm,
success: function(resp) {
console.log("Server said (response):\n '" + resp + "'");
$('#search-field').typeahead({source: resp});
},
error: function(e) {
console.log("Server said (error):\n '" + e + "'");
}
});
another update:
In Network tab the response gives the result I want but in this format: Resistance: Fall of ManResident Evil 4John Woo Presents StrangleholdAge of Empires II: The Age of KingsResident Evil 2. So without any formatting. Console.log(resp) gives me nothing though. Although when I search for "resident evil 6", that means when I type in the EXACT NAME, console.log also works.
Basically you should create key=>value store array and then in the end you should output it with json_encode. What you are doing wrong in your code is you are trying to echo and json_encode on every result which should be done just in the end.
post the code that initializes ajax request.
For example this is shorthand for jquery ajax function
$.ajax({
url: url,
dataType: 'json',
data: data,
success: callback
});
if data type specified json then callback function will receive an array like allCities in your example then you can pass it to your plugin. For example pseudo code:
$.ajax({
url: 'http://blabla',
dataType: 'json',
data: dataArray,
success: function(response) {
$('#city').typeahead({source: response, items:response.count()});
}
});
I am attempting to make a pie chart using a php file that gets the information from MySQL, JSON encodes it, and then sends it to my JS file to make the pie chart. I have looked at most of the other questions posted here and none of them help me at all. I have attempted to re-qrite my code to match ones that seem to fit, but nothing is working.
My php file is:
$shelvDate = $_POST['shelvDate'];
$x = 0;
// get information from database for shelving chart
$shelv = $conn -> query ("SELECT sum(quantity) as qty, date_process, created_by, first_name from inventory LEFT JOIN users on users.user_id =inventory.created_by
WHERE date_process = '$shelvDate' GROUP BY created_by" );
$num_rows = $shelv->num_rows;
if($num_rows > 0){
while($row = $shelv->fetch_assoc()) {
if($row['qty'] > 0){
$qtyArray[$x] = $row['qty'];
$nameArray[$x] = $row['first_name'];
}
$x++;
$pairs = array('first_name' => $nameArray, 'qty' => $qtyArray);
} // end of while statement
} //end of if statement
$conn->close();
echo json_encode(array($pairs));
When I attempt to get the data into my ajax/js I get an error. My JS is:
$("#getRecords").live('click', function() {
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
type: "POST",
async: false,
url: url,
dataType:"json",
data: ({shelvDate: $('#shelvDate').val()}),
success: function(data) {
for(var x=0; x<data.first_name.length; x++) {
var info = [data.first_name[x], data.qty[x]];
ret.push(info);
}
}); // end of ajax call
return ret;
}; // end of ajaxDataRenerer call
// The url for our json data
var jsonurl = "shelvChart.php";
var plot2 = $.jqplot('shelvChart', jsonurl,{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
title: "Books Shelved",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
I am don't know what I'm doing wrong or even where to go from here as I am still new to AJAX and JS. Any help will be greatly appreciated.
Jim
It would be very useful to see a real JSON string you are getting, cause I am not sure how you can get name[object,object],qty[object,object] after calling alert(ret) or maybe you are referring to other alert?.
Anyway from what you are saying your problem is that you must make sure that the array returned by the ajaxDataRenderer function is of a proper format that is accepted by a pie chart.
Therefore, for example, inside your PHP or JavaScript code you need to make sure that the returned array ret is of the following format:
ret = [[name[0], qty[0]], [name[1], qty[1]], ...];
This way all values that are in name array will be used as labels and qty array will be used as values from which the percentage will be evaluated.
Similar approach that shows how to prepare data for a chart is shown in this answer.
I'm getting two random values from a table. The values are in the same row.
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
echo $row["name"];
echo $row["surname"];
?>
And I want to display these two values at different div's on my HTML page by using jQuery Ajax functions.
$(function()
{
$("#sentence-form").submit(function()
{
$.ajax(
{
type: "GET",
url: "newperson.php",
success: function(response)
{
$("#top-container").append(response); /* Both name and surname */
}
});
});
});
The problem is separating two values to display different in div's. I tried to use two Ajax calls and I send boolean data to PHP to use with an if statement. So one of the Ajax calls displays name and the other one displays surname. But because of randomization, it's a bit complicated to find surname of a name.
What is a better approach?
Yes: send the data in a data structure – probably JSON – so your client-side code knows which bit is which.
First, send the data with PHP's json_encode function:
echo json_encode(array(
'name' => $row['name'],
'surname' => $row['surname']
));
Then use your browser's ability to parse JSON:
$.ajax({
type: "GET",
url: "newperson.php",
dataType: 'json',
success: function (response) {
$("#name-container").append(response.name);
$("#surname-container").append(response.surname);
}
});
response is now a Javascript object (something like {name: 'John', surname: 'Smith'}), so you can access the two parts as normal object members.
Send the variables as a JSON array
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
$output['name'] = $row["name"];
$output['surname'] = $row["surname"];
echo json_encode($output);
?>
And on the JavaScript code, access it as:
data.name and data.surname
Although I like lonesomeday's answer, and I think that that is the way to go, I will post the alternative:
Relevant PHP:
echo $row["name"].'||'.$row["surname"];
Relevant JavaScript code:
success: function (response) {
var parts = response.split('||');
$("#name-container").append(parts[0]); //name
$("#surname-container").append(parts[1]); //surname
}
Use this:
<?php
$result = mysql_query("SELECT * FROM people ORDER BY RAND() LIMIT 1", $connection);
$row = mysql_fetch_array($result);
echo $row["name"]."&".$row["surname"];
?>
$(function(){
$("#sentence-form").submit(function(){
$.ajax({
type : "GET",
url : "newperson.php",
success : function(response){
items=response.split('&')
$("#top-container").append(items[0]); /* name */
$('#bottom-container").append(items[1]); / /*s(u should be i)rname */
}
});
});
});