Highcharts pie charts can have url links - javascript

I am using Highcharts pie charts in my application, where the data for pie chart is populating from database. My question is after populating pie chart, if i click certain area it should render to particular php page. Is it possible?
here is my code :
function open_risk_level_pie()
{
$chart = new Highchart();
$chart->chart->renderTo = "open_risk_level_pie";
$chart->chart->plotBackgroundColor = null;
$chart->chart->plotBorderWidth = null;
$chart->chart->plotShadow = false;
$chart->title->text = "Risk Level";
$chart->tooltip->formatter = new HighchartJsExpr("function() {
return '<b>'+ this.point.name +'</b>: '+ this.point.y; }");
$chart->plotOptions->pie->allowPointSelect = 1;
$chart->plotOptions->pie->cursor = "pointer";
$chart->plotOptions->pie->dataLabels->enabled = false;
$chart->plotOptions->pie->showInLegend = 1;
$chart->plotOptions->pie->colors = array('red', 'orange', 'yellow', 'black');
$chart->credits->enabled = false;
// Open the database connection
$db = db_open();
// Get the risk levels
$stmt = $db->prepare("SELECT * from `risk_levels`");
$stmt->execute();
$array = $stmt->fetchAll();
$high = $array[0][0];
$medium = $array[1][0];
$low = $array[2][0];
// Query the database
$stmt = $db->prepare("select a.calculated_risk, COUNT(*) AS num, CASE WHEN a.calculated_risk >= " . $high . " THEN 'High' WHEN a.calculated_risk < " . $high . " AND a.calculated_risk >= " . $medium . " THEN 'Medium' WHEN a.calculated_risk < " . $medium . " AND a.calculated_risk >= " . $low . " THEN 'Low' WHEN a.calculated_risk < " . $low . " AND a.calculated_risk >= 0 THEN 'Insignificant' END AS level from `risk_scoring` a JOIN `risks` b ON a.id = b.id WHERE b.status != \"Closed\" GROUP BY level ORDER BY a.calculated_risk DESC");
$stmt->execute();
// Store the list in the array
$array = $stmt->fetchAll();
// Close the database connection
db_close($db);
// If the array is empty
if (empty($array))
{
$data[] = array("No Data Available", 0);
}
// Otherwise
else
{
// Create the data array
foreach ($array as $row)
{
$data[] = array($row['level'], (int)$row['num']);
}
$chart->series[] = array('type' => "pie",
'name' => "Level",
'data' => $data);
}
echo "<div id=\"open_risk_level_pie\"></div>\n";
echo "<script type=\"text/javascript\">";
echo $chart->render("open_risk_level_pie");
echo "</script>\n";
}

There is an exmaple on the highcharts website showing something similar. You can use the point/events/click function to trigger a new page load:
plotOptions: {
series: {
cursor: 'pointer',
point: {
events: {
click: function() {
location.href = this.options.url;
}
}
}
}
},
http://jsfiddle.net/w5Lx4/
Note, in this example, the URL is added to the series data:
data: [{
y: 29.9,
url: 'http://bing.com/search?q=foo'
}, {
You could replace this with generating a URL based on the point y value.

Related

My pagination is jumping around and I can't figure out how to fix it

I'm making a product listings page that uses AJAX calls to post the user's inputted data:
The pagination uses the jQuery inView function to call the next page
(NextPage.php) when loader.gif is in view
InfiniteScroll.js
$(document).ready(function() {
$('#Loader').on('inview', function(event, isInView) {
if (isInView) {
//Pagination
var nextPage = parseInt($('#pageno').val()) + 1;
//Filters
var minimum_wt = $('#hidden_minimum_wt').val();
var maximum_wt = $('#hidden_maximum_wt').val();
var shape = get_filter('shape');
var color = get_filter('color');
var enhancement = get_filter('enhancement');
var matching = get_filter('matching');
$.ajax({
type: 'POST',
url: 'vendors/php/NextPage.php',
data: {
pageno: nextPage,
minimum_wt: minimum_wt,
maximum_wt: maximum_wt,
shape: shape,
color: color,
enhancement: enhancement,
matching: matching
},
cache: false,
success: function(data) {
console.log(nextPage); //For debugging
if(data != '') {
$('#StoneContainer').append(data);
$('#pageno').val(nextPage);
} else {
$('.LoaderContainer').hide(); //Hide infinite scroll
}
}
});
}
});
});
//Checking applied filters
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function() {
filter.push($(this).val());
});
return filter;
}
NextPage.php
<?php
if(isset($_GET['pageno']) || isset($_POST['action'])) {
$pageno = $_GET['pageno'];
} else {
$pageno = $_POST['pageno'];
}
$limit = 10;
$offset = ($pageno-1) * $limit;
//Include database configuration file
include('dbConfig.php');
$SQL = "
SELECT
number,
image1,
wt,
TRUNCATE(length,1) as length,
TRUNCATE(width,1) as width,
CASE
WHEN stonetype = 'SA' THEN 'Sapphire'
WHEN stonetype = 'RU' THEN 'Ruby'
WHEN stonetype = 'TML-P' THEN 'Paraiba'
WHEN stonetype = 'EM' THEN 'Emerald'
WHEN stonetype = 'TS' THEN 'Tsavorite'
WHEN stonetype = 'SI' THEN 'Spinel'
WHEN stonetype = 'GT' THEN 'Garnet'
WHEN stonetype = 'BER' THEN 'Beryl'
WHEN stonetype = 'TML' THEN 'Tourmaline'
WHEN stonetype = 'KO' THEN 'Kornerupine'
ELSE 'n/a'
END AS 'stonetype',
CASE
WHEN enhcode = 'H' THEN 'Heated'
WHEN enhcode = 'N' THEN 'Unheated'
ELSE 'n/a'
END AS 'enhcode'
FROM
stones
WHERE
wt >= 2.5
";
if(isset($_POST["minimum_wt"], $_POST["maximum_wt"]) && !empty($_POST["minimum_wt"]) && !empty($_POST["maximum_wt"])) {
$SQL .= "
AND wt BETWEEN '".$_POST["minimum_wt"]."' AND '".$_POST["maximum_wt"]."'
";
}
if(isset($_POST["shape"])) {
$shape_filter = implode("','", $_POST["shape"]);
$SQL .= "
AND stoneshape IN('".$shape_filter."')
";
}
if(isset($_POST["color"])) {
$color_filter = implode("','", $_POST["color"]);
$SQL .= "
AND stonecolor IN('".$color_filter."')
";
}
if(isset($_POST["enhancement"])) {
$enhancement_filter = implode("','", $_POST["enhancement"]);
$SQL .= "
AND enhcode IN('".$enhancement_filter."')
";
}
if(isset($_POST["matching"])) {
$matching_filter = implode("','", $_POST["matching"]);
$SQL .= "
AND pair IN('".$matching_filter."')
";
}
$SQL .= "
ORDER BY
wt ASC
LIMIT
" . $offset. ",
" . $limit. "
";
$res_data = mysqli_query($db, $SQL);
if(isset($_POST["minimum_wt"], $_POST["maximum_wt"]) && !empty($_POST["minimum_wt"]) && !empty($_POST["maximum_wt"]) && isset($_POST["shape"]) && isset($_POST["color"]) && isset($_POST["enhancement"]) && isset($_POST["matching"])) {
while($row = mysqli_fetch_array($res_data)) {
echo '
<div class="Stone">
<!-- landing page -->
<a href="#ItemPage" class="ItemLink" rel="modal:open" id="' . $row['number']. '">
<!-- image -->
<div class="StoneData StoneIMG"> <img src="../../../' . $row['image1'] . '"> </div>
<!-- weight -->
<div class="StoneData">' . $row['wt'] . 'Ct</div>
<!-- type -->
<div class="StoneData">' . $row['stonetype'] . '</div>
<!-- enhancement -->
<div class="StoneData">' . $row['enhcode'] . '</div>
<!-- dimensions -->
<div class="StoneData">' . $row['length'] . ' x ' . $row['width'] . '</div>
<!-- item number -->
<div class="StoneData"># ' . $row['number'] . '</div>
</a>
</div>
';
}
}
?>
4 different check box fields and a jQuery range slider so the user
can filter out only the data they want
Filters.js
$(document).ready(function() {
filter_data();
function filter_data() {
var action = 'fetch_data';
//Pagination
var nextPage = parseInt($('#pageno').val()) + 0;
//Filters
var minimum_wt = $('#hidden_minimum_wt').val();
var maximum_wt = $('#hidden_maximum_wt').val();
var shape = get_filter('shape');
var color = get_filter('color');
var enhancement = get_filter('enhancement');
var matching = get_filter('matching');
$.ajax( {
url: 'vendors/php/Filters/FilterData.php',
method: 'POST',
data: {
action: action,
pageno: nextPage,
minimum_wt: minimum_wt,
maximum_wt: maximum_wt,
shape: shape,
color: color,
enhancement: enhancement,
matching: matching
},
async: true,
error:
function(jqXHR, strError) {
if(strError == 'timeout') {
// Do something. Try again perhaps?
alert('Seems like there was an error loading the filters request.');
}
},
success:
function(data) {
$('#StoneContainer').html(data);
$('#pageno').val(nextPage);
$('.LoaderContainer').show(); //Show infinite scroll
},
timeout: 3000
});
}
// Where to find values to be filtered
function get_filter(class_name) {
var filter = [];
$('.'+class_name+':checked').each(function() {
filter.push($(this).val());
});
return filter;
}
// Apply filter_data() of .common_selector
$('.common_selector').click(function() {
filter_data();
});
// Range slider
$('#wt_range').slider({
range: true,
values: [2.5, 30],
min: 2.5,
max: 30,
step: 0.1,
slide:
function(event, ui) {
// prevent thumbs from overlapping
if ((ui.values[1] - ui.values[0]) < 3) {
return false;
}
$('#wt_show').html(ui.values[0] + 'Ct - ' + ui.values[1] + 'Ct');
$('#hidden_minimum_wt').val(ui.values[0]);
$('#hidden_maximum_wt').val(ui.values[1]);
filter_data();
}
});
// open and close filters menu on mobile
if ($('#StoneContainer').width() < 420 ) {
$('.OpenCloseFilters').on('click', function() {
$('.FiltersContainer').slideToggle();
// refresh button
$('.ResetFiltersToggle0').toggleClass('ResetFiltersToggle1');
// change icon on toggle
$('#MenuIcon').toggleClass('mdi-menu-up mdi-menu-down');
});
}
});
FilterData.php
<?php
if(isset($_POST['pageno']) || isset($_POST['action'])) {
//Include database configuration file
include('../dbConfig.php');
$limit = 10;
$offset = !empty($_POST['pageno']) ? $_POST['pageno']: 0;
$SQL = "
SELECT
number,
image1,
wt,
TRUNCATE(length,1) as length,
TRUNCATE(width,1) as width,
CASE
WHEN stonetype = 'SA' THEN 'Sapphire'
WHEN stonetype = 'RU' THEN 'Ruby'
WHEN stonetype = 'TML-P' THEN 'Paraiba'
WHEN stonetype = 'EM' THEN 'Emerald'
WHEN stonetype = 'TS' THEN 'Tsavorite'
WHEN stonetype = 'SI' THEN 'Spinel'
WHEN stonetype = 'GT' THEN 'Garnet'
WHEN stonetype = 'BER' THEN 'Beryl'
WHEN stonetype = 'TML' THEN 'Tourmaline'
WHEN stonetype = 'KO' THEN 'Kornerupine'
ELSE 'n/a'
END AS 'stonetype',
CASE
WHEN enhcode = 'H' THEN 'Heated'
WHEN enhcode = 'N' THEN 'Unheated'
ELSE 'n/a'
END AS 'enhcode'
FROM
stones
WHERE
wt >= 2.5
";
if(isset($_POST["minimum_wt"], $_POST["maximum_wt"]) && !empty($_POST["minimum_wt"]) && !empty($_POST["maximum_wt"])) {
$SQL .= "
AND wt BETWEEN '".$_POST["minimum_wt"]."' AND '".$_POST["maximum_wt"]."'
";
}
if(isset($_POST["shape"])) {
$shape_filter = implode("','", $_POST["shape"]);
$SQL .= "
AND stoneshape IN('".$shape_filter."')
";
}
if(isset($_POST["color"])) {
$color_filter = implode("','", $_POST["color"]);
$SQL .= "
AND stonecolor IN('".$color_filter."')
";
}
if(isset($_POST["enhancement"])) {
$enhancement_filter = implode("','", $_POST["enhancement"]);
$SQL .= "
AND enhcode IN('".$enhancement_filter."')
";
}
if(isset($_POST["matching"])) {
$matching_filter = implode("','", $_POST["matching"]);
$SQL .= "
AND pair IN('".$matching_filter."')
";
}
$SQL .= "
ORDER BY wt ASC
LIMIT
$offset,
$limit
";
$result = mysqli_query($db, $SQL);
$output = '';
if(isset($_POST["minimum_wt"], $_POST["maximum_wt"]) && !empty($_POST["minimum_wt"]) && !empty($_POST["maximum_wt"]) && isset($_POST["shape"]) && isset($_POST["color"]) && isset($_POST["enhancement"]) && isset($_POST["matching"])) {
if($row = mysqli_fetch_array($result)) {
foreach($result as $row) {
$output .= '
<div class="Stone">
<!-- landing page -->
<a href="#ItemPage" class="ItemLink" rel="modal:open" id="' . $row['number']. '">
<!-- image -->
<div class="StoneData StoneIMG"> <img src="../../../' . $row['image1'] . '"> </div>
<!-- weight -->
<div class="StoneData">' . $row['wt'] . 'Ct</div>
<!-- type -->
<div class="StoneData">' . $row['stonetype'] . '</div>
<!-- enhancement -->
<div class="StoneData">' . $row['enhcode'] . '</div>
<!-- dimensions -->
<div class="StoneData">' . $row['length'] . ' x ' . $row['width'] . '</div>
<!-- item number -->
<div class="StoneData"># ' . $row['number'] . '</div>
</a>
</div>
';
}
}
} else {
$output = '
<h1 class="Error">
<span class="mdi mdi-filter-remove mdi-48px"></span>
NO STONES MATCH THAT
</h1>
';
}
echo $output;
}
?>
My problem is when the user updates the filters my pagination jumps to the next page so not only will they not see the else statement on FilterData.php (which can obviously be very confusing for the user) but they will get a totally blank page, even when there are some results.
I imagine the solution to be resetting to the first page (of my pagination) every time the data updates. But for some reason I can't figure out how to do it. I tried changing line 52 of Filters.js to $('#pageno').val(0);, but that didn't seem to work as expected.
I know this is probably a very simple issue for you guys and i'm sort of embarrassed even asking but I've been trying to fix this since last Wednesday and still can't get it (i'm pretty new to php). Thank you so much for your time in advance!

Scrollbar won't go down when chat window is created

I'm currently working on a chat application which will support up to four windows simultaneously.
When I open a new chat-window, the scrollbar won't go down even though the function is called. Whenever I send a message it works fine.
function createChat(caller_id) {
$.ajax({
type: 'POST',
url: 'create_chat_interface.php',
data: {
caller_id: caller_id,
},
success: function(data) {
if (!$('#chat-history-' + caller_id).length) {
if ($.trim($("#chat1").html()) == '') {
$('#chat1').html(data);
document.getElementById("chat-close").id = 'chat-close1';
} else if ($.trim($("#chat2").html()) == '') {
$('#chat2').html(data);
document.getElementById("chat-close").id = 'chat-close2';
} else if ($.trim($("#chat3").html()) == '') {
$('#chat3').html(data);
document.getElementById("chat-close").id = 'chat-close3';
} else if ($.trim($("#chat4").html()) == '') {
$('#chat4').html(data);
document.getElementById("chat-close").id = 'chat-close4';
}
$('#chat-input-' + caller_id).focus();
scrollDown(caller_id);
}
}
})
}
function fetch_chat_history($caller_id, $db)
{
$query = "SELECT * FROM messages WHERE from_id = '$caller_id'
OR to_id = '$caller_id' ORDER BY timestamp ASC";
$result = mysqli_query($db, $query);
$row = mysqli_fetch_assoc($result);
$output = '<ul>';
foreach ($result as $row) {
if ($row['from_id'] == $caller_id) {
$output .= '
<li class="received"><p>' . $row['message'] . '</p></li>';
} else {
$output .= '
<li class="sent"><p>' . $row['message'] . '</p></li>';
}
}
$output .= '</ul>';
return $output;
}

Drag and Drop using jQuery Save the new order

i'm using drag and drop to order a list with jquery ....
and i want to save the new order to Database by clicking a button for exemple
this is my methode to get list element
public function test() {
$choice = Database::getInstance()->query("SELECT * FROM choix WHERE condidat_concour_id = ".$this->data()->ID." ORDER BY ordre ASC");
foreach($choice->results() as $choi){
$cs_code = $choi->cs_code;
$cs = Database::getInstance()->query("SELECT code,designation,site
FROM cs
WHERE code = '{$cs_code}' ");
echo "<li id=".$choi->id.">";
echo "<span class='handle'><i class='fa fa-ellipsis-v'></i><i class='fa fa-ellipsis-v'></i></span>";
echo "<span class='text'>".$choi->cs_code."</span>";
echo "</li>";
}
}
I'm looking to use this Script to save order
function saveOrder() {
var articleorder="";
$("#sortable li").each(function(i) {
if (articleorder=='')
articleorder = $(this).attr('id');
else
articleorder += "," + $(this).attr('id');
});
//articleorder now contains a comma separated list of the ID's of the articles in the correct order.
$.post('set_order.php', { order: articleorder })
.success(function(data) {
alert('saved');
})
.error(function(data) {
alert('Error: ' + data);
});
but i don't know what i should use in set_order.php ??
i'm trying with this code but i didn't get any result !!
$i = 1 ;
$orderlist = explode(',', $_POST['ordre']);
foreach ($orderlist as $k=>$order) {
$sql = 'UPDATE choix SET ordre = :ordre WHERE id = :id' ;
$query = $pdo->prepare($sql);
$query->bindParam(':ordre', $i, PDO::PARAM_INT);
$query->bindParam(':id', $id, PDO::PARAM_INT);
$query->execute();
$i++ ;
}
you can check my Database classe here

Displaying existing content in editable textarea

Hi I am trying to make editable page with javascript and php and I want to display whats already stored in the area however it does not work. Its meant to be a blog page meaning that there are multiple posts. And I am unsure whether the problem is within the js or php.
This is the javascript I am using. The console.log() writes that post_id is unassigned.
$(document).on('click', '.editButton', function () {
var post_id = $(this).parent().data('id');
var self = this;
$.getJSON(settings.server, {post_id: post_id}, function(data){
var editableText = '<textarea class="editPostBody">' + data.body + '</textarea>';
console.log(post_id);
$(".post").parent().replaceWith(editableText);
});
});
var formatPost = function(d) {
var s = '';
s = '<div class="post" data-id="' + d.post_id + '"><h2 class="postHeading">' + d.title +'</h2>';
s += d.body;
s += '<p> Posted on: ' + d.date + '</p>';
s += '<div class="btn editButton">Edit Post</div>'
s += '</div>'
return s;
};
And this is the PHP file
connection to db established prior
if(count($_GET)) {
if(isset($_GET['post_id'])){
get_post_id( $_GET['post_id']);
}
}
else{
get_posts();
}
function get_posts() {
global $link;
// $sql = "SELECT COUNT(1) FROM posts";
// $result = mysqli_query($link, $sql);
// $total = mysqli_fetch_array($result);
$sql = "SELECT * FROM post ORDER BY date DESC LIMIT 0, 5";
$result = mysqli_query($link, $sql);
$rows = array();
while ($row = mysqli_fetch_assoc($result)) {
$rows[] = $row;
}
// $json = '{"total":"' . $total[0] . '","posts":';
$json = json_encode($rows);
// $json .= "}";
print($json);
}
function get_post_id($postId){
global $link;
$sql = "SELECT * FROM post WHERE id = $postId";
$result = mysqli_query($link, $sql);
$toSend = mysqli_fetch_assoc($result);
print json_encode($toSend);
}
Thank you
I modified the code like this
function get_post_id($postId){
global $link;
$sql = "SELECT * FROM post WHERE post_id = $postId";
$result = mysqli_query($link, $sql);
$toSend = mysqli_fetch_assoc($result);
print json_encode($toSend);
}
and JS
$(document).on('click', '.editButton', function () {
var post_id = $(this).parent().data('id');
// console.log(post_id);
var self = this;
$.getJSON(settings.server, {post_id: post_id}, function(data){
var editableText = $('<textarea class="editPostBody">' + data.body + '</textarea>');
console.log(post_id);
$(".post").parent().replaceWith(editableText);
});

Pagination jTable in PHP

How to use paging in jTable use PHP?
I have code below in employeeTable.php
<script src="jtable.2.4.0/jquery.jtable.min.js" type="text/javascript"></script>
//Get record count
$result = mysql_query("SELECT COUNT(*) AS RecordCount FROM employee;");
$row = mysql_fetch_array($result);
$recordCount = $row['RecordCount'];
//Get records from database
$result = mysql_query("SELECT * FROM employee ORDER BY '" . $_REQUEST["jtSorting"] . "' LIMIT '" . $_REQUEST["jtStartIndex"] . "','" . $_REQUEST["jtPageSize"] . "';");
//Add all records to an array
$rows = array();
while($row = mysql_fetch_array($result))
{
$rows[] = $row;
}
//Return result to jTable
$jTableResult = array();
$jTableResult['Result'] = "OK";
$jTableResult['TotalRecordCount'] = $recordCount;
$jTableResult['Records'] = $rows;
print json_encode($jTableResult);
Then I realize the problem is in here
$result = mysql_query("SELECT * FROM employee ORDER BY '" . $_REQUEST["jtSorting"] . "' LIMIT '" . $_REQUEST["jtStartIndex"] . "','" . $_REQUEST["jtPageSize"] . "';");
if I change $_REQUEST["jtSorting"] = rowname, $_REQUEST["jtStartIndex"] = number, $_REQUEST["jtPageSize"] = number, it works.
But if I don't change it, it shows 'An Error Occured While Communicating to the server'.
here is the code in jquery.jtable.min.js, when there are line about jtSorting, jtStartIndex, jtPageSize
/* Adds jtSorting parameter to a URL as query string.
*************************************************************************/
_addSortingInfoToUrl: function (url) {
if (!this.options.sorting || this._lastSorting.length == 0) {
return url;
}
var sorting = [];
$.each(this._lastSorting, function (idx, value) {
sorting.push(value.fieldName + ' ' + value.sortOrder);
});
return (url + (url.indexOf('?') < 0 ? '?' : '&') + 'jtSorting=' + sorting.join(","));
},
/* Overrides _createJtParamsForLoading method to add sorging parameters to jtParams object.
*************************************************************************/
_createJtParamsForLoading: function () {
var jtParams = base._createJtParamsForLoading.apply(this, arguments);
if (this.options.sorting && this._lastSorting.length) {
var sorting = [];
$.each(this._lastSorting, function (idx, value) {
sorting.push(value.fieldName + ' ' + value.sortOrder);
});
jtParams.jtSorting = sorting.join(",");
}
return jtParams;
}
});
})(jQuery);
Can anybody please help me understand?
I think you should go through this once.
Listaction jtable for Pagination and sorting table
It would require jQuery.Deferred to return data.
Handle it as
listAction: function (postData, jtParams) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/Employee_Controller/EmployeeList_method?jtStartIndex=' + jtParams.jtStartIndex + '&jtPageSize=' + jtParams.jtPageSize + '&jtSorting=' + jtParams.jtSorting,
type: 'POST',
dataType: 'json',
data: postData,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
Manually post values for it. I hope this maybe helpful.
the options will be received in $_GET object
like:
$jtStartIndex=$_GET['jtStartIndex'];
$jtPageSize=$_GET['jtPageSize'];
$jtSorting=$_GET['jtSorting'];
example:
$query="select * FROM products ORDER BY $jtSorting LIMIT $jtStartIndex, $jtPageSize;";
and in jtable settings:
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
sorting: true, //Enable sorting
defaultSorting: 'name ASC' ,
actions: {
listAction: 'data/products.php'//Set default sorting
},
...

Categories