Updating charts using Ajax

The retrieval of data from the server can be either by data-push or data-pull technologies. Since these topics are outside the scope of this book, we will limit ourselves to basic Ajax techniques. With Ajax, we can update a chart without the need to reload the whole page. This feature can be used to update charts when new data becomes available on the server.

In the following example, we will use Ajax to get data and update an already initialized chart at the click of a button. Contrary to the previous example, we will not mix our PHP and JavaScript code in this case, but rather will keep them in two separate files for better maintainability and readability.

We will use the same database and the same data as the previous example for the purpose of elaboration. Initially, our chart will be loaded with some random data. This can be considered as an initial state with the chart showing old data. As soon as an event occurs (in this case, a click), the client (browser) will request new data from the server; upon receiving that data, it will update the chart.

Initially, the chart is loaded with the current configuration:

var chartConfigOptions = {
  title: {
    text: 'Most Number of Movies by Actors'
  },
  chart: {
    type: 'column'
  },
  tooltip: {
    valueSuffix: ' Movies',
    useHTML: true
  },
  xAxis: {
    title: {
      text: 'Actor'
    },
    id: 'actor-names',
    categories: ['Jane', 'John', 'Doe']
  },
  yAxis: {
    title: {
      text: 'Movies'
    }
  },
  series: [{
    name: 'Actors',
    id: 'movie-count',
    data: [20, 10, 16]
  }]
};
$( '#actor_movies' ).highcharts( chartConfigOptions );

This will produce a simple column chart as shown in the following:

Updating charts using Ajax

We begin working on the Ajax part by creating the retrieve-data.php file that will contain PHP code to handle data retrieval from the database.

We create a new button in our main HTML as follows:

<button data-action="retrieve_data">Retrieve New Data</button>

The code for data-retrieval.php is as follows:

<?php

if( isset( $_POST ) ) {
  try {
    $con = new PDO( 'mysql:dbname=sakila;host=localhost', 'root', '' );
    $results = $con->query( 'SELECT first_name, last_name, COUNT(film_actor.actor_id) 
    FROM film_actor 
    JOIN actor 
    ON film_actor.actor_id = actor.actor_id 
    GROUP BY film_actor.actor_id 
    ORDER BY COUNT(film_actor.actor_id) DESC 
    LIMIT 10' );
  } catch ( PDOException $e ) {
    echo 'Connection failed: ' . $e->getMessage();
  }


  if( isset( $results ) ) {
    $data = [];
    $categories = [];
    $combined = [];

    foreach( $results as $row ) {
      array_push( $categories, $row['first_name'] );
      array_push( $data, (int) $row['COUNT(film_actor.actor_id)'] );
    }

    array_push( $combined, $data );
    array_push( $combined, $categories );

    header( 'Content-Type: application/json' );
    echo json_encode( $combined );
  }
}

We start by checking the $_POST super global variable to determine whether a request has been made. Next, inside a try-catch statement, we establish the connection to the database and execute a query just as we did in the previous example. If the query is successful, the results will be returned to the $results variable.

In the next step, we check whether any results have been returned by checking the $results variable. If there are returned results, we initialize two variables, that is $data and $categories, to hold series data and axis categories.

By iterating over $results, we collect categories and data in their separate arrays using PHP's array_push() method. Note that, in the case of $data, we typecast the current data point to an integer using (int). This is due to the fact that data can be interpreted as a string when fetching results from a query. Since we echoed the data inline in the previous example within the JavaScript code, typecasting it to an integer was not required there.

When both $data and $categories arrays are ready, we combine them into a single array, $combined, which we initialized earlier. In the next step, we set the header to JSON and echo out JSON representation of the $combined array. We will now write the JavaScript code to handle the request and receive JSON data from the server.

Since the request will initiate on the button click, we wrap our code inside an event handler method of click event for the button:

$( '[data-action="retrieve_data"]' ).on( 'click', function( e ) {
  e.preventDefault();
  $.ajax({
    type: 'POST',
    url: 'retrieve-data.php',
    beforeSend: function() {
      $( '#actor_movies' ).highcharts().showLoading();
    },
    success: function( data ) {
      var axis = $( '#actor_movies' ).highcharts().get( 'actor-names' ),
      series = $( '#actor_movies' ).highcharts().get( 'movie-count' );

      axis.setCategories( data[1], false );
      series.setData( data[0], false );
      $( '#actor_movies' ).highcharts().redraw();
    },
    complete: function() {
      $( '#actor_movies' ).highcharts().hideLoading();
    }
  })
});

In the preceding code, we send an Ajax request to the server using the jQuery.ajax() method. It accepts an object containing various properties of the request including the type and the url properties.

The beforeSend() function fires before sending the request and chart loading is shown using Highcharts' Chart.showLoading() method.

Upon success of the request, the success() method fires and accepts the returned data as the argument. The data returned from the server is composed of two arrays containing data points and categories, respectively.

Next, using the Chart.get() method, we get the axis and series by using their IDs. Their references are stored in the axis and series variables, respectively.

In the next step, we set the axis categories and series data using the Axis.setCategories() and Series.setData() methods. In both of the methods, we set the second redraw argument to false as we manually redraw the chart using the Chart.redraw() method.

Finally, the complete() callback fires after the invocation of the success (or error) method. At this point, we remove the chart loading using the Chart.hideLoading() method.

You can learn more about the jQuery.ajax() method by visiting the following link:

http://api.jquery.com/jQuery.ajax/

The chart produced after clicking on the button is the same as the previous example.

In this section, we learned to create Ajax requests to receive data from the server and dynamically update the chart with new data. We used a couple of Highcharts API methods including Axis.setCategories() and Series.setData(). In the next section, we will learn about Highcharts' export module.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.189.180.43