0

I have created a MySQL database and I am running xampp locally.

Here is my data.php:

<?php
//setting header to json
header('Content-Type: application/json');

//database
define('DB_HOST', 'localhost');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'products');

//get connection
$mysqli = new mysqli(DB_HOST, DB_USERNAME, DB_PASSWORD, DB_NAME);

if(!$mysqli){
 die("Connection failed: " . $mysqli->error);
}

//query to get data from the table
$query = sprintf("SELECT date, url, price FROM table1");

//execute query
$result = $mysqli->query($query);

//loop through the returned data
$data = array();
foreach ($result as $row) {
 $data[] = $row;
}

//free memory associated with result
$result->close();

//close connection
$mysqli->close();

//now print the data
print json_encode($data);

The output file generates the date, price and url

When I then take a look at my barchart.html, I am trying to introduce a onclick link to url when user clicks on each bar.

$(document).ready(function(){
 $.ajax({
  url: "http://192.168.64.2/fs/data.php",
  method: "GET",
  success: function(data) {
   console.log(data);
   var date = [];
   var price = [];

   for(var i in data) {
    date.push("" + data[i].date);
    price.push(data[i].price);
   }

   var chartdata = {
    labels: date,
    datasets : [
     {
      label: 'price',
      backgroundColor: 'rgba(200, 200, 200, 0.75)',
      borderColor: 'rgba(200, 200, 200, 0.75)',
      hoverBackgroundColor: 'rgba(200, 200, 200, 1)',
      hoverBorderColor: 'rgba(200, 200, 200, 1)',
      data: price,
     }
    ]
                
   };

   var ctx = $("#mycanvas");

   var barGraph = new Chart(ctx, {
    type: 'bar',
    data: chartdata
   });
  },
  error: function(data) {
   console.log(data);
  }
 });
});

This is the bar chart which is generated;

enter image description here

When I hover over the bar chart, the date and price show up, however on click, I want to send user to url, as pulled from the table1 in data.php

croco88
  • 45
  • 4
  • is there one URL for the whole chart or separate URLs per bar? – souzan Feb 17 '19 at 11:11
  • separate urls per bar where I currently have this part of the code: success: function(data) { console.log(data); var date = []; var price = []; i should be just able to pull out the urls from: var url = []; i think? – croco88 Feb 17 '19 at 11:21
  • check the first answer to this question: https://stackoverflow.com/questions/41852585/chart-js-clickable-bar // as well as the third comment on that answer. It should do what you need – souzan Feb 17 '19 at 11:24
  • I tried adding the OnClick function after var chartdata = { }, but nothing appears to happen – croco88 Feb 17 '19 at 13:12

0 Answers0