I think this is a case of me not knowing javascript, but I can't for the love of god get this to work
For some reason, creating vars cancels out my java alert code. (maybe bc its wrong)
And my java vars aren't being set correctly.
I pointed out the problems in my comments
In my SQL, I have Temperatures all with an associative value disk 'id'.
So my data structure in this is:
$array[id];
$array[id]=array();
//For every new element
//Using while ($row = mysql_fetch_assoc($result))
$array[id][]="temperature";
//second id
$array[id2];
$array[id2]=array();
//For every new element
$array[id2][]="temperature";
$array[id2][]="temperature2";
$array[id2][]="temperature3";
$array[id2][]="temperature4";
MY ATTEMPT (WRONG CODE):
//I simplified this code down. In my own version, the join works ONLY when I use an actual index "174" instead of a javascript variable that is 174. Couldnt get join to be alerted in this simplified version
<?php
$phparray=array();
$phparray["100"]="First Element";
$phparray["101"]="Second Element";
$phparray["102"]="Third Element";
$phparray["100"]=array();
$phparray["101"]=array();
$phparray["100"][]="First Element - Sub 2";
$phparray["100"][]="First Element - Sub 3";
$phparray["101"][]="Second Element - Sub 2";
echo $phparray["100"]; //Does not show 'First Element'. Shows Array
echo $phparray["100"][0]; //Correctly shows sub element
//var_dump($phparray);
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Associative Array in PHP used in Java Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
var index=100;
//var index2=<?php echo $phparray[index]; ?>; //Supposed to output 'First Element'
var joined=[<?php echo join($phparray[index], ', '); ?>]; //Supposed to join elements of '100'
alert("hello"); //This line does not work anymore after the var index2 made above
</script>
</head>
<body>
<div id="container" style="height: 500px; min-width: 600px"></div>
</body>
</html>
EDIT: Here is the long full code of my php page:
<?php
include_once("../../config.php");
$conn=mysql_connect($dbhost,$dbuser,$dbpasswd) or die ('Error connecting to mysql');
mysql_select_db($dbname);
ini_set('error_reporting', E_ALL);
//ini_set('display_errors',1);
ini_set('log_errors',1);
$sql = "select disk_id from disk";
$result = mysql_query($sql);
$ids = array();
$names=array();
$temperatures = array();
while ($row = mysql_fetch_assoc($result)) {
$ids[] = $row['disk_id'];
$temperatures[]=$row['disk_id'];
//echo "<br>".$row['disk_id'];
}
//
foreach ($ids as $value)
{
//echo "--START ".$value."--<br>";
$sql = "select * from disk_data WHERE disk_id=".$value;
$result = mysql_query($sql);
$dates=array();
$key = array_search($value, $temperatures);
$temperatures[$value] = array();
//var_dump($temperatures);
while ($row = mysql_fetch_assoc($result))
{
$temps = $row['Temperature'];
$temp = explode("||", $temps);
$prehex=$temp[3];
$posthex=hexdec(substr($prehex,-2));
$predate=$row['create_date'];
$postdate =strtotime($predate)*1000;
$output="[".$postdate.", ".$posthex."]";
//$temperatures[$key][] = $output;
$temperatures[$value][] = $output;
$dates[]=$row['create_date'];
//echo $row['create_date']." ".end($temperatures[$key])."<br>";
}
}
print_r(array_keys($array));
var_dump($temperatures);
foreach ($ids as $value)
{
//echo $value;
$key = array_search($value, $temperatures);
//echo "Key: $key; Value: $temperatures[$value]<br />\n";
$comma = join($temperatures[$value],", ");
echo $comma;
echo "\n";
}
?>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var seriesOptions = [],
yAxisOptions = [],
seriesCounter = 0,
//names=[<?php echo join($ids, ', '); ?>],
names=["174"], //Above code works. BUT only using ID 174 to test
values=[<?php echo join($temperatures["174"], ', '); ?>], //Supposed to be ALL data. But temp 174
colors = Highcharts.getOptions().colors;
//alert(values);
$.each(names, function(i, name2) {
//alert(seriesOptions.length);
alert(name2.toString()); //Works....
var values=[<?php
echo join($temperatures[name2], ', '); ?>]; //Doesnt work
//alert(values);
console.log(values);
//document.write(values);
seriesOptions[i] =
{
name: name2,
data:values
};
// As we're loading the data asynchronously, we don't know what order it will arrive. So
// we keep a counter and create the chart when all the data is loaded.
seriesCounter++;
if (seriesCounter == names.length)
{
createChart();
}
});
// create the chart when all data is loaded
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 0
},
title: {
text: 'Test Performance Data',
style: {
margin: '10px 100px 0 0' // center it
}
},
yAxis: {
title: {text:'Temperature (°C)'},
labels: {
formatter: function() {
return this.value + '';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
line: {
gapSize: 0
},
series: {
//compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
yDecimals: 2
},
series: seriesOptions
});
}
});
</script>
</head>
<body>
<script type="text/javascript" src="../js/highstock.js"></script>
<script type="text/javascript" src="../js/themes/gray.js"></script>
<div id="container" style="height: 500px; min-width: 600px"></div>
</body>
</html>
You cannot mix PHP and JavaScript like that. JavaScript variables are not parsed in PHP.
Even when index is replaced by a variable $index or 100, your code would still miss quotes.
Use the following instead:
<script type="text/javascript">
var index=100;
var array = <?php echo json_encode($phparray); ?>;
var joined = array[index];
The last line outputs the following:
var joined={"100":["First Element - Sub 2","First Element - Sub 3"],"101":["Second Element - Sub 2"],"102":"Third Element"};
Before trying this, make sure that you remove the invalid comment in the line after var index = 100;. Otherwise, a PHP warning can be generated, which invalidates the code:
var index=100;
//var index2=PHP Notice: Use of undefined constant index - assumed 'index' in /tmp/t.php on line 29
PHP Notice: Undefined index: index in /tmp/t.php on line 29
Look at the generated code in the client browser, you'll find that it looks like this:
var joined = [First Element - Sub2, Second Element etc.....]
note the lack of quotes around your inserted strings. You've created Javascript syntax errors, which kills the entire <script> block those variables are embedded within.
As Rob W mentions above, you have to use json_encode() to produce VALID javascript out of your arbitrary text.
As a general rule, if you've got PHP generating anything javascript, and especially when filling in variables like that, use json_encode() - it'll keep these kinds of headaches away.
PHP runs server side and will output its content in to the webpage, before its then rendered in your browser and the JavaScript is run. (meaning when php is running, it has no idea what "index" is because as far as its concerned its never been defined.
I expect what you want to do is move your PHP in to javascript so you can then access it however you like in the page. In your JavaScript just add somthing along the lines of this:
var my_array_in_js = <?php echo json_encode($phparray); ?>;
Which will result in PHP printing its array as json, which can then be read by javascript however you want. Then to read a specific index just use
alert(my_array_in_js[index]);
Related
I am using google charts (on a php webpage) with data from an sql DB. The problem i am having is that it is not display the field names and values properly it simply displays the value of the first field "expense". It should be showing two fields "expense" and "income" with the values in the db. Any ideas what i am doing wrong ?
my code below:
<?php
$dbhandle = new mysqli('localhost','root','','useraccounts');
echo $dbhandle->connect_error;
$query = "SELECT * FROM ctincome";
$res = $dbhandle->query($query);
?>
<html>
<head>
<script type="text/javascript"
src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load("current", {packages:["corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['expense','income'],
<?php
while($row=$res->fetch_assoc())
{
echo "['".$row['expense']."','".$row['income']."'],";
}
?>
]);
var options = {
title: 'Expenses to Income',
pieHole: 0.4,
};
var chart = new
google.visualization.PieChart(document.getElementById
('donutchart'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="donutchart" style="width: 900px; height: 500px;"></div>
</body>
</html>
the values for the income column should be numbers, not strings.
remove the single quotes from the second column.
from...
echo "['".$row['expense']."','".$row['income']."'],";
to...
echo "['".$row['expense']."',".$row['income']."],";
I have three suggestions based on my experience in crossbrowser or javascript bugs I solved.
First point : You are just echoing, you need to use concatenation.
<?php
$data = '';
while($row=$res->fetch_assoc())
{
$data .= "['".$row['expense']."','".$row['income']."'],";
}
?>
var data = google.visualization.arrayToDataTable([
['expense','income'],
<?php echo $data; ?>
]);
second point : In javascript last comma may or may not work, its best to not to append comma if it's a last row.
var data = google.visualization.arrayToDataTable([
['expense','income'],
<?php
while($row=$res->fetch_assoc())
{
if(last row )
$data .= "['".$row['expense']."','".$row['income']."']";
else $data .= "['".$row['expense']."','".$row['income']."'],";
}
?>
]);
third suggestion : check data type of var data before and after the concatenation
I have a mysql database containing multiple columns of power values captured over time, with time captured in the first column. I would like to plot the power values and display the time of day on the x-axis of a Highcharts chart. I am currently able to display the multiple Power values on the y-axis but I am unable to get the time of day to display on the chart. Here is the PHP code that partially works:
<?php
// Connect to database
$con = mysqli_connect("localhost","userid","passwd","power_readings");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Set the variable $rows to the columns Energy_Date and Total_watts
$query = mysqli_query($con,"SELECT Energy_Date,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Total_watts'];
}
// Set the variable $rows1 to the columns Energy_Date and Power_watts
$query = mysqli_query($con,"SELECT Energy_Date,Power_watts FROM combined_readings");
$rows1 = array();
$rows1['name'] = 'Neurio_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows1['data'][] = $tmp['Power_watts'];
}
// Set the variable $rows2 to the columns Energy_Date and Solar_watts
$query = mysqli_query($con,"SELECT Energy_Date,Solar_watts FROM combined_readings");
$rows2 = array();
$rows2['name'] = 'Solar_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows2['data'][] = $tmp['Solar_watts'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
Can someone tell me how to change the code to pass the values from the time of day column properly?
Here is what the chart currently looks like:
When I made changes to the PHP to add the 'Energy_Date' field to the array passed to Highcharts (shown below) it results in a blank chart.
The array consists of fields that look like this (a time stamp followed by a power reading, separated by period:
"2018-02-21 16:56:00.052","2018-02-21 16:59:00.052","2018-02-21 17:02:00.039","2018-02-21 17:05:00.039","2018-02-21 17:08:00.039"
<?php
// Connect to database
$con = mysqli_connect("localhost","userid","passwd","power_readings");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// Set the variable $rows to the columns Energy_Date and Total_watts
$query = mysqli_query($con,"SELECT Energy_Date,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_Date'].$tmp['Total_watts'];
}
// Set the variable $rows1 to the columns Energy_Date and Power_watts
$query = mysqli_query($con,"SELECT Energy_Date,Power_watts FROM combined_readings");
$rows1 = array();
$rows1['name'] = 'Neurio_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows1['data'][] = $tmp['Energy_Date'].$tmp['Power_watts'];
}
// Set the variable $rows2 to the columns Energy_Date and Solar_watts
$query = mysqli_query($con,"SELECT Energy_Date,Solar_watts FROM combined_readings");
$rows2 = array();
$rows2['name'] = 'Solar_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows2['data'][] = $tmp['Energy_Date'].$tmp['Solar_watts'];
}
$result = array();
array_push($result,$rows);
array_push($result,$rows1);
array_push($result,$rows2);
print json_encode($result, JSON_NUMERIC_CHECK);
mysqli_close($con);
?>
The html receiving this array looks like this:
<!DOCTYPE html>
<html lang="en">
<title>Combined Values Graph</title>
<head>
<meta http-equiv="refresh" content="180">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
var x_values = [];
var chart;
$(document).ready(function() {
Highcharts.setOptions({
colors: ['#4083e9', '#99ccff', '#00ffff', '#e6e6e6', '#DDDF00', '#64E572', '#FF9655', '#FFF263', '#6AF9C4']
});
$.getJSON("values.php", function(json) {
chart = new Highcharts.Chart({
chart: {
renderTo: 'mygraph',
type : 'spline',
borderWidth: 1,
zoomType: 'x',
panning: true,
panKey: 'shift',
plotShadow: false,
marginTop: 100,
height: 500,
plotBackgroundImage: 'gradient.jpg'
},
plotOptions: {
series: {
fillOpacity: 1
}
},
plotOptions: {
series: {
marker: {
enabled: false
}
}
},
title: {
text: 'Combined Power Readings'
},
subtitle: {
text: 'Total = Neurio + Solar Readings in Watts'
},
xAxis : {
title : {
text : 'Time of Day'
}
},
yAxis: {
title: {
text: 'Power (watts)'
},
plotLines: [{
value: 0,
width: 2,
color: '#ff0000',
zIndex:4,
dashStyle: 'ShortDot'
}]
},
tooltip: {
formatter: function() {
return '<b>'+ this.series.name +'</b><br/>'+
this.x +': '+ this.y;
}
},
legend: {
layout: 'vertical',
align: 'right',
verticalAlign: 'top',
x: -10,
y: 120,
borderWidth: 1
},
plotOptions : {
spline : {
marker : {
radius : 0,
lineColor : '#666666',
lineWidth : 0
}
}
},
series: json
});
});
});
});
</script>
<script src="https://code.highcharts.com/highcharts.src.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
</head>
<body>
<div class="container" style="margin-top:20px">
<div class="col-md-10">
<div class="panel panel-primary">
<div class="panel-body">
<div id ="mygraph"></div>
</div>
</div>
</div>
</div>
</body>
</html>
I have added the console statement to the bottom of the js like so:
series: json
});
console.log(json);
});
Here's what is shown in the browser console for PHP version 1 (The version that displays the graphs).
Browser console 1
Here's what is shown in the browser console for PHP version 2 (The version that gives a blank chart).
Browser console 2
Thanks for your helpful suggestions. I have changed the while loops to look like this:
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = $tmp['Energy_UTC'];
$rows['data'][] = $tmp['Total_watts'];
}
The output of the PHP now looks like this:
[{"name":"Total_watts","data":[1519315164,93,1519315344,354]},{"name":"Neurio_watts","data":[1519315164,76,1519315344,309]},{"name":"Solar_watts","data":[1519315164,17,1519315344,45]}]
The data being passed to Highcharts (from the console) now looks like this:
Browser console 3
The chart is still wrong: the x-axis is not showing the timestamps and the chart is incorrect. Can anyone suggest how to change the PHP or html to correct this?
OK, I have updated the while loops to look like this:
$query = mysqli_query($con,"SELECT Energy_UTC,Total_watts FROM combined_readings");
$rows = array();
$rows['name'] = 'Total_watts';
while($tmp = mysqli_fetch_array($query)) {
$rows['data'][] = [$tmp['Energy_UTC'],$tmp['Total_watts']];
}
The PHP output now looks like this:
[{"name":"Total_watts","data":[[1519387869,423],[1519388049,423],[1519388229,332],[1519388410,514],[1519388590,514]...
and the chart is now displaying UTC timestamps for each power value.
You are writing a large block of code with many duplicated components. I've taken the time to DRY your method. It is best practice to minimize calls to the database, so I've managed to combine your queries into one simple select.
Theoretically, you will only need to modify $colnames_labels to modify your HighChart. I have written inline comments to help you to understand what my snippet does. I have written some basic error checks to help you to debug if anything fails.
Code: (untested)
$colnames_labels=[
'Total_watts'=>'Total_watts',
'Power_watts'=>'Neurio_watts',
'Solar_watts'=>'Solar_watts'
];
$select_clause_ext=''; // declare as empty string to allow concatenation
foreach($colnames_labels as $colname=>$label){
$data[]=['name'=>$label]; // pre-populate final array with name values
// generates: [0=>['name'=>'Total_watts'],1=>['name'=>'Neurio_watts'],2=>['Solar_watts']]
$select_clause_ext.=",$colname";
// generates: ",Total_watts,Power_watts,Solar_watts"
}
$subarray_indexes=array_flip(array_keys($colnames_label)); // this will route resultset data to the correct subarray
// generates: ['Total_watts'=>0,'Power_watts'=>1,'Solar_watts'=>2]
if(!$result=mysqli_query($con,"SELECT UNIX_TIMESTAMP(Energy_Date) AS Stamp{$select_clause_ext} FROM combined_readings ORDER BY Energy_Date")){
$data=[['name'=>'Syntax Error (query error)','data'=>[0,0]]; // overwrite data with error message & maintain expected format
}elseif(!mysqli_num_rows($result)){
$data=[['name'=>'Logic Error (no rows)','data'=>[0,0]];
}else{
while($row=mysqli_fetch_assoc($result)){
foreach($subarray_indexes as $i=>$col){
$data[$i]['data'][]=[$row['Stamp'],$row[$col]]; // store [stamp,watts] data in appropriate subarrays
}
}
}
echo json_encode($data,JSON_NUMERIC_CHECK); // Convert to json (while encoding numeric strings as numbers) and print to screen
I have the following Google Charts code and I'm trying to connect it with MySQL, I have tried each and everything with it available on the internet but it still shows just one entry of SQL result set, although I have 10 entries in it. On the internet I found the $row_num counter thing and since including it in my code, I have been able to query one entry but I want to query all entries with it. Please help me with this and let me know what mistake (if any) I have been making, Following is my PHP code:
[<?php
``$dbhandle= new mysqli('localhost','root','8317','record');
//echo $dbhandle->connect_error();
$query= "SELECT * from download_manager";
$res= $dbhandle->query($query);
?>
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':\['bar'\]});
google.charts.setOnLoadCallback(drawStuff);
function drawStuff() {
var data = new google.visualization.arrayToDataTable(\[
\['Title', 'No. of Downloads'\],
<?php
$total_rows = mysqli_num_rows($res);
$row_num = 0;
if (mysqli_num_rows($res) > 0) {
while($row=$res->fetch_assoc())
{
$row_num++;
if ($row_num == $total_rows){
echo "\['".$row\['filename'\]."',".$row\['downloads'\]."\]";
}
}
}
else
{
echo "0 results";
}
?>
\]);
var options = {
width: 800,
chart: {
'title': 'Top 10 Downloads',
subtitle: 'for the last month'
},
bars: 'horizontal', // Required for Material Bar Charts.
axes: {
}
};
var chart = new google.charts.Bar(document.getElementById('dual_x_div'));
chart.draw(data, options);
};
</script>
</head>
<body>
See Also : Downloads in the Last 7 Years <br> <br>
<div id="dual_x_div" style="width: 900px; height: 500px;"></div>
</body>
</html>][1]
You have missed adding a comma , in your PHP data loop. Try with the following:
echo "\['".$row\['filename'\]."',".$row\['downloads'\]."\],";
I have been at this some time trying to get highcharts to chart some data returned by php. I have done many searches and nothing works. I can write the php to deliver the data however it needs to be but how do you get it to dynamically chart it?????
I can deliver it as:
[["1372875867","44.8782806"],["1372875885","46.2020226"]]
or
[[1372876686,44.0655823],[1372876693,43.3360596], etc ]
but how do I get the data from the php output into the dyname example they display?????
!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Highstock Example</title>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
Highcharts.setOptions({
global : {
useUTC : false
}
});
// Create the chart
window.chart = new Highcharts.StockChart({
chart : {
renderTo : 'container',
events : {
load : function() {
// set up the updating of the chart eachsecond
var series = this.series[0];
setInterval(function() {
var x = (new Date()).getTime(),
y = Math.round(Math.random() * 100);
series.addPoint([x, y], true, true);
}, 1000);
}
}
},
rangeSelector: {
buttons: [{
count: 1,
type: 'minute',
text: '1M'
}, {
count: 5,
type: 'minute',
text: '5M'
}, {
type: 'all',
text: 'All'
}],
inputEnabled: false,
selected: 0
},
title : {
text : 'Live random data'
},
exporting: {
enabled: false
},
series : [{
name : 'Random data',
data : (function() {
// generate an array of random data
var data = [], time = (new Date()).getTime(), i;
for( i = -999; i <= 0; i++) {
data.push([
time + i * 1000,
Math.round(Math.random() * 100)
]);
}
return data;
})()
}]
});
});
</script>
</head>
<body>
<script src="../../js/highstock.js"></script>
<script src="../../js/modules/exporting.js"></script>
<div id="container" style="height: 500px; min-width: 500px"></div>
</body>
</html>
my current php is:
<?php
// include("$_SERVER[DOCUMENT_ROOT]/config/config.php");
include("adodb5/adodb.inc.php");
$connection = new COM("ADODB.Connection") or die("Cannot start ADO");
$result_set = $connection->Execute("
SELECT tag, TIME, value
FROM picomp
WHERE TIME >= '*-3m' AND tag = 'xxx:xx_xxx.xxx'
");
$result_count = 0;
// $labels = array();
while (!$result_set->EOF) {
$pidate = date("U", strtotime($result_set->fields[1]) );
if ($result_count <> 0){
print ",";
}else{
print "[";
}
print "[".$pidate.",".$result_set->fields[2]."]";
// array_push("{$result_set->fields[2]}");
$result_count = $result_count +1;
$result_set->MoveNext();
// echo "testing";
}
print "];";
You can use HighchartsPHP which is a wrapper for Highcharts, which basically allows you to write all that JS code in PHP. It's very useful and pretty simple to use.
HighchartsPHP on GitHub
Your timestamp should be multiplied by 1000, and both values should be numbers.
Please familair with soultion, how to prepare JSON, because you only print "as JSON", but it is not.
Take look at http://php.net/manual/en/function.json-encode.php where some examples are introduced.
I have been messing with this for too long trying to get it to work. Can anyone please see if you have any pointers.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="autocomplete.css" />
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<style>
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script>
$(function() {
$( "#materials" ).autocomplete({
source: "autocomplete.php",
minLength: 2
});
});
</script>
<div class="demo">
<div class="ui-widget">
<label for="materials">Materials: </label>
<input id="materials" />
</div>
</div><!-- End demo -->
</body>
</html>
and the php file is
require_once "db_con.php"; // Database connection, I know this works.
$q = strtolower($_GET["q"]);
if (!$q)
return;
$sql = "SELECT * FROM materials WHERE name LIKE '%$q%'";
$rsd = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
while ($rs = mysqli_fetch_array($rsd)) {
$cname = $rs['name']; // I know this all returns correctly
echo json_encode($cname); // First time I have ever used json, error might be here.
}
I am trying to have a webpage with an autocomplete powered by Jquery that is supplied data from mysql using PHP. Simples. Only its not working...
Anyone have any ideas what I am missing ?
Regards
---- EDIT ----
In order to check this was working I completed the following:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="autocomplete.css" />
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="jquery-ui-1.8.21.custom.min.js" type="text/javascript"></script>
<title></title>
</head>
<body>
<style>
.ui-autocomplete-loading { background: white url('images/ui-anim_basic_16x16.gif') right center no-repeat; }
</style>
<script>
$(function() {
$( "#materials" ).autocomplete({
source: <?php
include_once 'db_con.php';
$sql = "SELECT name FROM materials";
$rsd = mysqli_query($dbc, $sql) or die(mysqli_error($dbc));
echo '[';
while ($rs = mysqli_fetch_array($rsd)) {
echo "'" . $rs['name'] . "', "; //add results to array
}
echo ']';
?>,
minLength: 2
});
});
</script>
<div class="demo">
<div class="ui-widget">
<label for="materials">Materials: </label>
<input id="materials" />
</div>
</div><!-- End demo -->
</body>
</html>
Which works perfectly. So good infact I think im going to keep this code not quite how its supposed to work but...
Try this code, Its works for me
$().ready(function() {
$("#materials").autocomplete("autocomplete.php", {
width: 260,
matchContains: true,
autoFill:true,
selectFirst: false
});
});
In the PHP part, maybe try something like that:
$res = array(); //create a new array
while ($rs = mysqli_fetch_array($rsd)) {
$res[] = (string)$rs['name']; //add results to array, casted as string
}
header('Content-type: application/json'); //add JSON headers (might work w/o)
echo json_encode($res); //output array as JSON
...that way you should have all results in one array like
['name1', 'name2', 'name3']
Your PHP is all wrong:
while ($rs = mysqli_fetch_array($rsd)) {
$cname = $rs['name']; // I know this all returns correctly
echo json_encode($cname); // First time I have ever used json, error might be here.
}
Should be:
$cname = array();
while ($rs = mysqli_fetch_array($rsd)) {
$cname[]['label'] = $rs['name']; // I know this all returns correctly
break;
}
echo json_encode($cname); // First time I have ever used json, error might be here.
label is the default label field within an array row that is used by jqueryautocomplete (I believe). Also the return must be an array of arrays each array row representing a match.
You can make it more complicated by adding a value field for what to make the textbox to actually equal to by doing:
$cname = array();
while ($rs = mysqli_fetch_array($rsd)) {
$cname[]['label'] = $rs['name']; // I know this all returns correctly
$cname[]['value'] = $rs['id'];
break;
}
echo json_encode($cname); // First time I have ever used json, error might be here.
Of course I don't think your actually wanting the break; I put this in because:
while ($rs = mysqli_fetch_array($rsd)) {
$cname = $rs['name']; // I know this all returns correctly
echo json_encode($cname); // First time I have ever used json, error might be here.
}
Denotes to me that you are actually returning a single row from your results. If you are not and are actually returning all results then take the break; out.
to handle a json answer from a php ajax call i customize the source function and handle the result myself this way:
$(function() {
$( "#materials" ).autocomplete({
source: function(request, response){
$.post("autocomplete.php", {
term: request.term
}, function(data){
if (data.length == 0) {
data.push({
label: "No result found",
});
}
response($.map(data, function(item){
return {
label: item.name,
value: item.name
}
}))
}, "json");
},
minLength: 2,
dataType : "json"});
});