I have problem with connecting my mysql database to Highstock chart
Here is my code - it does not show anything when I run it shows just empty page
Can someone tell me what I am doing wrong or send me example for the script with database connection?
I would really appreciate
<!DOCTYPE HTML>
<html>
<body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="../../code/highstock.js"></script>
<script src="../../code/modules/exporting.js"></script>
<div id="container" style="height: 400px; min-width: 310px"></div>
<script type="text/javascript">
<?php $conn=mysqli_connect("localhost:3307","sampleuser","samplepass","sampledatabase");
if(!$conn)
{
die("connection in error:".mysqli_connect_error());
}
$result=mysqli_query($conn,"Select time,open,close,high,low,volume From sampletable ");
while ($row = mysql_fetch_array($result)) {
extract $row;
$time *= 1000; // convert from Unix timestamp to JavaScript time
$data[] = "[$time,$open,$close,$high,$low,$volume]";
}
?>
Highcharts.stockChart('container', {
title: {
text: 'AAPL stock price by minute'
},
rangeSelector: {
buttons: [{
type: 'hour',
count: 1,
text: '1h'
}, {
type: 'day',
count: 1,
text: '1D'
}, {
type: 'all',
count: 1,
text: 'All'
}],
selected: 1,
inputEnabled: false
},
series: [{
name: 'AAPL',
type: 'candlestick',
data: data,
tooltip: {
valueDecimals: 2
}
}]
});
</script>
</body>
</html>
I've created a table based on the http://www.jtable.org template, my table, and most of the functionality is up and running, however I run into a problem when I want to include a search bar to filter tables results as I type. The problem I believe lies in the fact that most tables I've created using php have created the actual html table in the code so td's and tr's for example, and the search functionality would key off of matching these terms.
Currently however my table is being generated on the front end, without the actual HTML content in the back end, so I am unable to search. Is there any method I can use to search this table with this code, maybe using server side processing, or something else I'm unaware of?
This is the code I'm using:
<html>
<title> title </title>
<head>
<link href="themes/redmond/jquery-ui-1.8.16.custom.css" rel="stylesheet" type="text/css" />
<link href="scripts/jtable/themes/metro/darkgray/jtable.css" rel="stylesheet" type="text/css" />
<script src="scripts/jquery-1.6.4.min.js" type="text/javascript"></script>
<script src="scripts/jquery-ui-1.8.16.custom.min.js" type="text/javascript"></script>
<script src="scripts/jtable/jquery.jtable.js" type="text/javascript"></script>
</head>
<body>
<div class="filtering">
<body>
<input type="text" style="background-color: #e6ffff;" placeholder="Search Any Column" size="70" id="search";/>
</body>
<div id="PeopleTableContainer" style="width: relative;" ></div>
<img src="Sharks-2-Trans-30-150623-2.png" width="150" height="43" style="float:bottom-right; opacity: 10;">
<script type="text/javascript">
$(document).ready(function () {
//Prepare jTable
$('#PeopleTableContainer').jtable({
title: 'ICS Central',
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
sorting: true, //Enable sorting
defaultSorting: 'ISO_Name ASC', //Set default sorting
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
//selectOnRowClick: false, //Enable this to only select using checkboxes
actions: {
listAction: 'PersonActions2.php?action=list',
createAction: 'PersonActions2.php?action=create',
updateAction: 'PersonActions2.php?action=update',
deleteAction: 'PersonActions2.php?action=delete'
},
fields: {
PersonId: {
key: true,
create: false,
edit: false,
list: false
},
ISO_Name: {
title: 'ISO Name',
width: '5%'
},
ICS_Defect: {
title: 'Defect #',
width: '5%'
},
Abstract: {
title: 'Abstract',
width: '30%'
},
problem_description: {
title: 'Problem Description',
width: '30%'
},
fix_description: {
title: 'Fix Description',
width: '30%'
},
levels_approved: {
title: 'Levels Approved',
width: '30%'
},
reboot_required: {
title: 'Reboot Required?',
width: '30%'
},
reapplied_after_ccl: {
title: 'Reapplied After CCL?',
width: '30%'
},
reapplied_after_hmc_rebuild: {
title: 'Reapplied After HMC Rebuild?',
width: '30%'
},
bundle_fix_cmvc: {
title: 'Bundle Fix CMVC',
width: '30%'
}
},
//Register to selectionChanged event to hanlde events
selectionChanged: function () {
//Get all selected rows
var $selectedRows = $('#PeopleTableContainer').jtable('selectedRows');
$('#SelectedRowList').empty();
if ($selectedRows.length > 0) {
//Show selected rows
$selectedRows.each(function () {
var record = $(this).data('record');
$('#SelectedRowList').append(
'<b>ISO_Name</b>: ' + record.ISO_Name +
'<br /><b>Abstract</b>:' + record.Abstract + '<br /><br />'
);
});
} else {
//No rows selected
$('#SelectedRowList').append('No row selected! Select rows to see here...');
}
},
// rowInserted: function (event, data) {
// if (data.record.ISO_Name.indexOf('Add_Info_HB_v1.0.iso') >= 0) {
// $('#PeopleTableContainer').jtable('selectRows', data.row);
//}
//}
});
//Load student list from server
$('#PeopleTableContainer').jtable('load');
//Delete selected students
$('#DeleteAllButton').button().click(function () {
var $selectedRows = $('#PeopleTableContainer').jtable('selectedRows');
$('#PeopleTableContainer').jtable('deleteRows', $selectedRows);
});
});
</script>
</body>
</html>
I use a search text field and filter the result on keyUp, but that is not client side filtering. It makes the ajax call to the list action and uses a variable searchname to do its filtering. We use Hibernate and have a line of code that filters from the DB like: " obj.name like '%searchname%' "
<body>
<div class="filtering">
Name: <input type="text" id="search"/>
</div>
<body>
...
...
<script type="text/javascript">
$(document).ready(function () {
...
$('#search').keyup(function(){
$('#PeopleTableContainer').jtable('load', {searchname: $(this).val()});
});
}
In my project I'm using DataTables to display my data, which is retrieved from an PHP echo json_encode. The PHP page is a script that returns JSON:
{
"sig1_re": [
{
"Ticket_RT": 716771,
"Cable_de_renvoi": 45,
"Longueur_de_ligne_(Selt)": 50,
"Res_LigneCoupee": "short",
"Ticket_fils": 152321,
"Numero_ND": "",
"Gamot_DateFermeture": "",
"Difference_de_date": "",
"Supprimer": "<a class='delete'><button>Delete</button></a>"
},
{
"Ticket_RT": 716760,
"Cable_de_renvoi": 45,
"Longueur_de_ligne_(Selt)": 67,
"Res_LigneCoupee": "open",
"Ticket_fils": "",
"Numero_ND": "",
"Gamot_DateFermeture": "",
"Difference_de_date": "",
"Supprimer": "<a class='delete'><button>Delete</button></a>"
}
],
"bad_nd": [
{
"Ticket_RT": 716620,
"Numero_ND": 236598741,
"Supprimer": "<a class='delete'><button>Delete</button></a>"
},
{
"Ticket_RT": 716577,
"Numero_ND": 565231583,
"Supprimer": "<a class='delete'><button>Delete</button></a>"
}
]
}
In my first attempt I had one JS file for each table in my HTLM and that works great, but I repeat the same code a lot and call the JSON echo each time, so I decided to regroup all my code in one JS file.
I managed to export almost all the tables options but I'm having trouble defining some variables; one is hideFromExport: I need to only copy the values from the first columns when I click on "COPY" button. The second problem is with oTable which I use to delete the row. I would like to set these two variables to be compatible with all my tables. (in my below example I use only two tables but in the actual project I have more).
Live Example: http://live.datatables.net/peceqofo/1/edit
Code:
<!DOCTYPE html>
<html>
<head>
<link href="https://raw.githubusercontent.com/twbs/bootstrap/master/dist/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://raw.githubusercontent.com/FortAwesome/Font-Awesome/master/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<div class="container" style="width: 90%;">
<div class="panel panel-danger" style="margin: 5px;">
<div class="panel-heading">
<h2 class="panel-title">
<b>My Test</b>
</h2>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="tableA" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Ticket_RT</th>
<th>Cable_de_renvoi</th>
<th>Longueur_de_ligne_</th>
<th>Res_LigneCoupee</th>
<th>Ticket_fils RT</th>
<th>Gamot_DateFermeture</th>
<th>Numero_ND</th>
<th>Gamot_DateFermeture</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<br />
<table id="tableB" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%">
<thead>
<tr>
<th>Ticket_RT</th>
<th>Numero_ND</th>
<th>Supprimer</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.js"></script>
<script src="https://raw.githubusercontent.com/Stuk/jszip/master/dist/jszip.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/pdfmake.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.12/dataRender/ellipsis.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
var jsonData = {};
$.ajax({
url: "http://www.json-generator.com/api/json/get/bUHEbjuIoi?indent=2",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
console.log(jsonData);
var hideFromExport = [1, 2, 3]; /*<--- How i can custom this for each table individually ?? */
var options = {
responsive: true,
bAutoWidth: true,
dom: '<"top"lf>Bt<"bottom"pi><"clear">',
scrollY: 400,
scrollCollapse: true,
jQueryUI: true,
bProcessing: true,
sScrollX: "70%",
sScrollXInner: "100%",
bScrollCollapse: true,
bDestroy: true,
searching: false,
iDisplayLength: 25,
buttons: [{ /*<--- How i can custom this for each table individually ?? */
extend: 'copyHtml5',
exportOptions: {
columns: function(idx, data, node) {
var isVisible = table.column(idx).visible();
var isNotForExport = $.inArray(idx, hideFromExport) !== -1;
return isVisible && !isNotForExport ? true : false;
}
}
},
'excelHtml5', 'csvHtml5', 'pdfHtml5'
],
language: {
url: "https://cdn.datatables.net/plug-ins/1.10.12/i18n/French.json",
buttons: {
copy: 'Copier Tickets',
copyTitle: 'Ajouté au presse-papiers',
copyKeys: 'Appuyez sur <i>ctrl</i> ou <i>\u2318</i> + <i>C</i> pour copier les données du tableau à votre presse-papiers. <br><br>Pour annuler, cliquez sur ce message ou appuyez sur Echap.',
copySuccess: {
_: 'Copiés %d rangs',
1: 'Copié 1 rang'
}
}
}
};
function initialize(jsonData) {
/* --- TableA INIT --- */
options.aaData = jsonData.sig1_re;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Cable_de_renvoi" },
{ "mData": "Longueur_de_ligne_(Selt)" },
{ "mData": "Res_LigneCoupee" },
{ "mData": "Ticket_fils" },
{ "mData": "Gamot_DateFermeture" },
{ "mData": "Numero_ND" },
{ "mData": "Gamot_DateFermeture" },
{ "mData": "Supprimer" }
];
options.aoColumnDefs = [
{ "title": "Titre 1", "targets": 0 },
{ "title": "Titre 2", "targets": 1 },
{ "title": "Titre 3", "targets": 2 },
{ "title": "Titre 4", "targets": 3 },
{ "title": "Titre 5", "targets": 4 },
{ "title": "Titre 6", "targets": 5 },
{ "title": "Titre 7", "targets": 6 },
{ "title": "Titre 8", "targets": 7 },
{ "title": "Titre 9", "targets": 8 }
/*{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }*/
];
$("#tableA").dataTable(options);
/* --- TableB INIT --- */
options.aaData = jsonData.bad_nd;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Numero_ND" },
{ "mData": "Supprimer" }
];
options.aoColumnDefs = [
{ "title": "Titre 01", "targets": 0 },
{ "title": "Titre 02", "targets": 1 },
{ "title": "Titre 03", "targets": 2 },
{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }
];
$("#tableB").dataTable(options);
}
initialize(jsonData);
var oTable = $('#tableA').DataTable(); /*<--- How i can custom this for each table individually ?? */
$('#tableA').on('click', 'a.delete', function (e) {
oTable.row($(this).parents('tr')).remove().draw();
});
// Permet de réduire les commentaires et ajouter tooltip
$.fn.DataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
var esc = function ( t ) {
return t
.replace( /&/g, '&' )
.replace( /</g, '<' )
.replace( />/g, '>' )
.replace( /"/g, '"' );
};
return function ( d, type, row ) {
// Order, search and type get the original data
if ( type !== 'display' ) {
return d;
}
if ( typeof d !== 'number' && typeof d !== 'string' ) {
return d;
}
d = d.toString(); // cast numbers
if ( d.length < cutoff ) {
return d;
}
var shortened = d.substr(0, cutoff-1);
// Find the last white space character in the string
if ( wordbreak ) {
shortened = shortened.replace(/\s([^\s]*)$/, '');
}
// Protect against uncontrolled HTML input
if ( escapeHtml ) {
shortened = esc( shortened );
}
return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'…</span>';
};
};
});
</script>
</body>
</html>
Solution :
Well after a lot of research i found an solution for the commun button options, now that works good ! Then I have added a button that will delete your selected row(s).
I hope this code will help more guys in the same situation like me !
Enjoy :)
Code :
<!DOCTYPE html>
<html>
<head>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/1.10.12/css/jquery.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/responsive/2.1.0/css/responsive.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://cdn.datatables.net/buttons/1.2.2/css/buttons.dataTables.css" rel="stylesheet" type="text/css" />
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="css/bfm.css">
<meta charset=utf-8 />
<title>DataTables - JS Bin</title>
</head>
<body>
<div class="container" style="width: 90%;">
<div class="panel panel-danger" style="margin: 5px;">
<div class="panel-heading">
<h2 class="panel-title">
<b>My Test</b>
</h2>
</div>
<div class="panel-body">
<div class="table-responsive">
<table id="tableA" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%"></table>
<br />
<table id="tableB" class="table table-striped table-hover dt-responsive display nowrap" cellspacing="0" width="100%"></table>
</div>
</div>
</div>
</div>
<script src="http://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<script src="https://cdn.datatables.net/responsive/2.1.0/js/dataTables.responsive.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/dataTables.buttons.js"></script>
<script src="https://raw.githubusercontent.com/Stuk/jszip/master/dist/jszip.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/pdfmake.min.js"></script>
<script src="https://raw.githubusercontent.com/bpampuch/pdfmake/master/build/vfs_fonts.js"></script>
<script src="https://cdn.datatables.net/buttons/1.2.2/js/buttons.html5.min.js"></script>
<script src="https://cdn.datatables.net/plug-ins/1.10.12/dataRender/ellipsis.js"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready( function () {
var jsonData = {}; // get the json object array from php
$.ajax({
url: "http://www.json-generator.com/api/json/get/bTKebXDGdK?indent=2",
async: false,
dataType: 'json',
success: function(data) {
jsonData = data;
}
});
console.log(jsonData);
var buttonCommon = { // set default export column 0 (first column)
exportOptions: {
columns:[0]
}
};
var options = { // set options for tables
responsive: true,
bAutoWidth: true,
dom: '<"top"lf>Bt<"bottom"pi><"clear">',
scrollY: 400,
scrollCollapse: true,
jQueryUI: true,
bProcessing: true,
sScrollX: "70%",
sScrollXInner: "100%",
bScrollCollapse: true,
bDestroy: true,
searching: false,
iDisplayLength: 25,
buttons: [
$.extend( true, {}, buttonCommon, {
header: false,
extend: 'copyHtml5'
}),
'excelHtml5', 'csvHtml5', 'pdfHtml5',
{
text: 'Delete',
action: function ( e, dt, node, config ) { // function to delete selected rows on click button
dt.data().rows('.selected').remove().draw( false );
}
}
],
language: {
url: "json/French.json",
buttons: {
copy: 'Copy',
copyTitle: 'Ajouté au presse-papiers',
copyKeys: 'Appuyez sur <i>ctrl</i> ou <i>\u2318</i> + <i>C</i> pour copier les données du tableau à votre presse-papiers. <br><br>Pour annuler, cliquez sur ce message ou appuyez sur Echap.',
copySuccess: {
_: 'Copiés %d rangs',
1: 'Copié 1 rang'
}
}
}
};
function initialize(jsonData) {
/* --- TableA INIT --- */
options.aaData = jsonData.sig1_re;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Cable_de_renvoi" },
{ "mData": "Longueur_de_ligne_(Selt)" },
{ "mData": "Res_LigneCoupee" },
{ "mData": "Ticket_fils" },
{ "mData": "Gamot_DateFermeture" },
{ "mData": "Numero_ND" },
{ "mData": "Difference_de_date" }
];
options.aoColumnDefs = [
{ "title": "Titre 1", "targets": 0 },
{ "title": "Titre 2", "targets": 1 },
{ "title": "Titre 3", "targets": 2 },
{ "title": "Titre 4", "targets": 3 },
{ "title": "Titre 5", "targets": 4 },
{ "title": "Titre 6", "targets": 5 },
{ "title": "Titre 7", "targets": 6 },
{ "title": "Titre 8", "targets": 7 }
/*{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) }*/
];
$("#tableA").dataTable(options);
/* --- TableB INIT --- */
options.aaData = jsonData.bad_nd;
options.aoColumns = [
{ "mData": "Ticket_RT" },
{ "mData": "Numero_ND" }
];
options.aoColumnDefs = [
{ "title": "Titre 01", "targets": 0 },
{ "title": "Titre 02", "targets": 1 },
{ "targets": 1, "render": $.fn.DataTable.render.ellipsis(5) } // call function to render + tooltip
];
$("#tableB").dataTable(options);
}
initialize(jsonData);
$('#tableA tbody').on( 'click', 'tr', function () { // set multi select rows
$(this).toggleClass('selected');
});
$('#tableB tbody').on( 'click', 'tr', function () { // set multi select rows
$(this).toggleClass('selected');
});
// Function to delimit render + tootil
$.fn.DataTable.render.ellipsis = function ( cutoff, wordbreak, escapeHtml ) {
var esc = function ( t ) {
return t
.replace( /&/g, '&' )
.replace( /</g, '<' )
.replace( />/g, '>' )
.replace( /"/g, '"' );
};
return function ( d, type, row ) {
// Order, search and type get the original data
if ( type !== 'display' ) {
return d;
}
if ( typeof d !== 'number' && typeof d !== 'string' ) {
return d;
}
d = d.toString(); // cast numbers
if ( d.length < cutoff ) {
return d;
}
var shortened = d.substr(0, cutoff-1);
// Find the last white space character in the string
if ( wordbreak ) {
shortened = shortened.replace(/\s([^\s]*)$/, '');
}
// Protect against uncontrolled HTML input
if ( escapeHtml ) {
shortened = esc( shortened );
}
return '<span class="ellipsis" title="'+esc(d)+'">'+shortened+'…</span>';
};
};
});
</script>
</body>
</html>
I would suggest to keep the tables separate with attributes. And if you would like to add extra columns and buttons in data tables. You can achieve that using following approach.
Add an extra column for action.
On fnRowCallback method add specific class to the action column.
Example of click on action:
jQuery('#datatable tbody').on('click', 'td.action', function () {
//call custom method to format the data inside td.action column.
data = {
'id': $(this).attr('cour_id')
};
tr.after(format(data)).show();
});
It will create action button for each row with specific row ids and attributes and won't conflict with each other.
Hope it will help!
I tried to use the example given in highcharts website. But when i use it all i am getting is a blank html page. Someone please help me with the code. I do not understand why the code is not loading properly please tell me if i should add something extra to this, and please do let me know how to use a php array to make this graph work also
<html>
<head>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script>
$(function () {
var chart;
$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'Browser market shares at a specific website, 2010'
},
tooltip: {
pointFormat: '{series.name}: <b>{point.percentage}%</b>',
percentageDecimals: 1
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
color: '#000000',
connectorColor: '#000000',
formatter: function() {
return '<b>'+ this.point.name +'</b>: '+ this.percentage +' %';
}
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data: [
['Firefox', 45.0],
['IE', 26.8],
{
name: 'Chrome',
y: 12.8,
sliced: true,
selected: true
},
['Safari', 8.5],
['Opera', 6.2],
['Others', 0.7]
]
}]
});
});
});
</script>
</head>
<body>
<div id="container" style="min-width: 400px; height: 400px; margin: 0 auto"></div>
</body>
</html>
I believe your problem is in the order you included the scripts. Try placing jQuery first:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
Demo (working / not working).
Update: to load your data from MySQL using PHP, please see this example. However, as you pointed out yourself, encoding it using JSON might be a better option:
$data = array();
while($row = mysql_fetch_array($results)) {
$data[] = array($row[1], $row[0]);
}
echo json_encode($data);
This last echo can be used either to return the whole array using ajax (like the linked example above), or when generating the page itself (i.e. "hardcoding" it in the script):
series: [{
type: 'pie',
name: 'Browser share',
data: <?php echo json_encode($data)?>
}]
This will work since your array, when JSON encoded, can be used in place of a JavaScript literal (and the json_encode should take care of escaping everything, preventing XSS vulnerabilities).
The order of including javascripts should be:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
By this I mean, you have to include the jQuery library first before any other script.
I'm trying to realize an input field which shows suggestions while typing. I've found the jquery autocomplete function, but I'm struggling with XML as data source coming from php. My php file creates an output like this.
XML:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<locations>
<location>
<number>600</number>
<name>Location Name 600</name>
</location>
<location>
<number>698</number>
<name>Location Name 698</name>
</location>
<location>
<number>1110</number>
<name>Location Name 1110</name>
</location>
</locations>
I've tried it with the link posted by Rory McCrossan.
My HTML now looks like this:
<!DOCTYPE HTML>
<head>
<title>Autocomplete</title>
<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.8.20.custom.min.js"></script>
<script type="text/javascript">
$(function() {
function log( message ) {
$( "<div/>" ).text( message ).prependTo( "#output" );
$( "#output" ).scrollTop( 0 );
}
$.ajax({
url: "api.php",
dataType: "xml",
success: function(xmlResponse) {
var data = $("location", xmlResponse).map(function() {
return {
name: $("name", this).text(),
number: $("number", this).text()
};
}).get();
$("#locations").autocomplete({
source: data,
minLength: 0,
select: function( event, ui ) {
log( ui.item ?
"Selected: " + ui.item.name + ", number: " + ui.item.number :
"Nothing selected, input was " + this.value );
}
});
}
});
});
</script>
</head>
<body style="background-color: black; color: white;">
<input id="locations" />
<div class="ui-widget" style="margin-top:2em; font-family:Arial">
Result:
<div id="output" style="height: 200px; width: 300px; overflow: auto;" class="ui-widget-content"></div>
</div>
</body>
</html>
When I write something into the input field, and then clear it, it shows me 3 li's below the input field (which is the amount of locations I have, according to the xml), but there's no text being display next to them. What's going wrong?
To use XML with autoComplete, see the example here: http://jqueryui.com/demos/autocomplete/xml.html
Ok, found a solution for myself (decided to create JSON output). Rory McCrossan's example was nice, but from what I could see, it just loaded the xml once, and then searched within the xml. What I wanted was prefiltered output, so it wouldn't transfer too much data.
$(function() {
$("#locations").autocomplete({
source: function(request, response) {
$.ajax({
url: "api.php",
dataType: "jsonp",
data: {
location: request.term
},
success: function(data) {
response($.map(data.locations, function(item) {
return {
label: item.name,
value: item.nummer
}
}));
}
});
},
minLength: 0,
select: function(event, ui) {
$("<div/>").text(ui.item.label + " " + ui.item.value).prependTo("#output");
}
})
})