Highcharts – load JSON data via Ajax and PHP!

highcharts-ajax-php

Highcharts is a popular JavaScript for creating easy and interactive charts, but you know it is also possible to make it dynamic by pulling the data from the database using server-side scripts. In this tutorial I have used PHP as a server-side script, you can use any other technology  such as ASP, ASP.NET, Ruby, etc.,

Let’s see JavaScript first:

<script>
$(function () {

		//on page load  
		getAjaxData(1);

		//on changing select option
		$('#dynamic_data').change(function(){
			var val = $('#dynamic_data').val();
			getAjaxData(val);
		});

		function getAjaxData(id){

		//use getJSON to get the dynamic data via AJAX call
		$.getJSON('data.php', {id: id}, function(chartData) {
			$('#container').highcharts({
				chart: {
					type: 'column'
				},
				title: {
					text: 'Highcharts - Pulling data from PHP using Ajax'
				},
				xAxis: {
					categories: ['One', 'Two', 'Three']
				},
				yAxis: {
					min: 0,
					title: {
						text: 'Value'
					}
				},
				series: chartData
			});
		});
	}
});
</script>

If you see, I’m using getJSON() for ajax call, because Highcharts needs JSON data to create charts. Then I have created a function called getAjaxData(), which helps to load dynamic data to the Highcharts without reloading the page.

Here is the entire HTML (index.html):

<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
<style>
	#dynamic_data{
		border: 1px solid gray;
		border-radius: 10px;
		padding: 10px;
		text-decoration:none;
		float:left;
		margin:4px;
		text-align:center;
		display: block;
		color: green;
	}
</style>
<script>
$(function () {

		//on page load  
		getAjaxData(1);

		//on changing select option
		$('#dynamic_data').change(function(){
			var val = $('#dynamic_data').val();
			getAjaxData(val);
		});

		function getAjaxData(id){

		//use getJSON to get the dynamic data via AJAX call
		$.getJSON('data.php', {id: id}, function(chartData) {
			$('#container').highcharts({
				chart: {
					type: 'column'
				},
				title: {
					text: 'Highcharts - Pulling data from PHP using Ajax'
				},
				xAxis: {
					categories: ['One', 'Two', 'Three']
				},
				yAxis: {
					min: 0,
					title: {
						text: 'Value'
					}
				},
				series: chartData
			});
		});
	}
});
</script>
</head>
<body>
<h3><a href="https://blog.theonlytutorials.com/highcharts-pass-data-dynamically-jquery/">Go back to the Tutorial</a></h3>
<select id="dynamic_data">
	<option value="0">Select Data</option>
	<option value="1" selected>Data 1</option>
	<option value="2">Data 2</option>
	<option value="3">Data 3</option>
</select>
<div id="container" style="width: 50%;min-width: 310px; height: 400px; margin: 0 auto"></div>
</body>
</html>

And here is the PHP file (data.php):

<?php
//connect to database
$mysqli = new mysqli("localhost","my_user","my_password","my_db");

// Check connection
if ($mysqli -> connect_errno) {
  echo "Failed to connect to MySQL: " . $mysqli -> connect_error;
  exit();
}

$id = $_GET['id'];

//define array
//we need two arrays - "male" and "female" so $arr and $arr1 respectively!
$arr 	= array();
$arr1 	= array();
$result = array();

//get the result from the table "highcharts_data"
$sql = "select * from higcharts_data where map_id = $id";
$q = $mysqli -> query($sql);
$j = 0;
while($row = $q->fetch_assoc()){

//highcharts needs name, but only once, so give a IF condition
	if($j == 0){
	$arr['name'] = 'Male';
	$arr1['name'] = 'Female';
		$j++;
	}
	//and the data for male and female is here
	$arr['data'][] = $row['male'];
	$arr1['data'][] = $row['female'];
}

//after get the data for male and female, push both of them to an another array called result
array_push($result,$arr);
array_push($result,$arr1);

//now create the json result using "json_encode"
print json_encode($result, JSON_NUMERIC_CHECK);

$mysqli -> close();
?>

PHP file is used to connect to the MySQL database, pull the data from the table, and print it as a JSON result. To understand the PHP file just read the comments in it.

And the MySQL dump data for table “highcharts_data“:

--
-- Table structure for table `higcharts_data`
--

CREATE TABLE IF NOT EXISTS `higcharts_data` (
  `h_id` int(10) NOT NULL AUTO_INCREMENT,
  `male` int(10) NOT NULL,
  `female` int(10) NOT NULL,
  `map_id` int(10) NOT NULL,
  PRIMARY KEY (`h_id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=11 ;

--
-- Dumping data for table `higcharts_data`
--

INSERT INTO `higcharts_data` (`h_id`, `male`, `female`, `map_id`) VALUES
(1, 100, 75, 1),
(2, 500, 550, 1),
(3, 300, 250, 1),
(4, 510, 501, 2),
(5, 654, 654, 2),
(6, 878, 987, 2),
(7, 600, 500, 3),
(8, 300, 600, 3),
(9, 654, 515, 3);

Finally, to make it easier for you here is the DEMO and DOWNLOAD links:

demo download

15 thoughts on “Highcharts – load JSON data via Ajax and PHP!

  1. Hi,
    nice tutorial!
    I tried you code and somethings strange happened! if the data coming from server using data.php doesn’t works; the only way is to copy paste the debug output from eclipse in a file named data.php or data.json
    I don’t understand why doesn’t works with data extracts direct from database even if data.php provides the right data.

    thanks in advance for your help my name is Mauro and I’m writing from Italy

    1. Check if the data.php actually prints the JSON results. Check your PHP version.
      if you see my code i’m doing JSON_NUMERIC_CHECK to encode numeric strings as numbers and it required at least 5.3.3 to work.
      print json_encode($result, JSON_NUMERIC_CHECK);

      1. Hi, there. How do you modify this tutorial to have different types of charts (lines, columns etc) with data from different tables (6 columns in a table f.ex.). ? Best regards

  2. Hello
    Thanks for your script which is very interesting.
    I tried to adapt it to create a pie. It works except for the name of each category where Highcharts writes ‘Slice’ and not the name of the category. Could you help me. Can I send you my script ?
    Thanks Olivier

  3. Hi, i did a copy pass of your code and inspire by my own code to populate my highchart of line type, but i have a problem with my data.php. It shows ‘Undefined index: id’ because of this i can’t get my JSON . I think the problem is about the AJAX request to send the url. But i can’t find the solution. I hope that you can help me figure out my problem. I really appreciate !

    Thanks in advance !

  4. Hi , I am new to highchart. I have tried the above example, but when I am running the data.php in localhost, it is not showing any json data. Also I have created the schema and all the credentials are correct. Please help me as it is very requirement for me .

    Thanks in Advance.!!

  5. I Get a blank page , data.php returns json strings , but i am unable to see any plot
    kindly help , i love your tutorials , they are easy to undestand , please help Thanks

  6. can you update this tutorial into mysqli because mysql are deprecated for the update version of php.

    And thank you very much for this tutorial

Leave a Reply

Theme: Overlay by Kaira
Agurchand