Populate Highcharts with JSON data using jQuery

Hello everyone!

Graphs and charts help make information easier to visualize. Developers can display charts for better analysis and understanding. Highcharts help develop interactive JavaScript charts for web pages. It is basically a charting library written in pure JavaScript, offering an easy way of adding charts to your web site or web application.

Through this post, we will learn how to populate and display a bar chart dynamically using JSON data received via a RESTful web service.

Pre-requisites: Eclipse IDE, Notepad , Apache Tomcat 7

Step 1: Create dynamic web project

Let’s first create a web project that exposes a web service to send JSON data. Launch Eclipse IDE and create a Dynamic Web Project called TestHttpJson. Create a new Service class called DataService and add the following code!

DataService.java

package com.example;

import java.util.HashMap;
import java.util.Map;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Response;
import org.json.JSONArray;
import org.json.JSONObject;

@Path("/rest")
public class DataService {

	@Context org.jboss.resteasy.spi.HttpResponse response;
	@Path("/json")
	@Produces("application/json")
	@GET
	public Response getJSONData() {

		Map<String, String> data1 = new HashMap<String,String>();
		data1.put( "key", "Computers");
		data1.put( "value","114");

		Map<String, Object> data2 = new HashMap<String, Object>();
		data2.put( "key", "Electronics");
		data2.put( "value","214");

		Map<String, Object> data3 = new HashMap<String, Object>();
		data3.put( "key", "Mechanical");
		data3.put( "value","514");

		JSONObject json1 = new JSONObject(data1);
		JSONObject json2 = new JSONObject(data2);
		JSONObject json3 = new JSONObject(data3);

		JSONArray array = new JSONArray();
		array.put(json1);
		array.put(json2);
		array.put(json3);

		JSONObject finalObject = new JSONObject();
		finalObject.put("student_data", array);

		response.getOutputHeaders().putSingle("Access-Control-Allow-Origin", "*");
		return Response.status(200).entity(finalObject.toString()).build();
	}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
	id="WebApp_ID" version="3.0">
	<display-name>TestHttpJson</display-name>
	<welcome-file-list>
		<welcome-file>index.html</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<!-- Auto scan REST service -->
	<context-param>
		<param-name>resteasy.scan</param-name>
		<param-value>true</param-value>
	</context-param>

	<context-param>
		<param-name>resteasy.servlet.mapping.prefix</param-name>
		<param-value>/</param-value>
	</context-param>

	<listener>
		<listener-class>
			org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap</listener-class>
	</listener>

	<servlet>
		<servlet-name>resteasy-servlet</servlet-name>
		<servlet-class>
			org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
	</servlet>

	<servlet-mapping>
		<servlet-name>resteasy-servlet</servlet-name>
		<url-pattern>/*</url-pattern>
	</servlet-mapping>

</web-app>

Note: You need to include the REST API specific jars before running the application. Please refer this post for more information.

Now, run the project on the Tomcat server and enter the following URL,

http://localhost:8080/TestHttpJson/rest/json

You should see the JSON data in the browser page.

output_3

Step 2: Create HTML page

Next, we need to use HighCharts API to create our bar chart using JSON data of the web service. The jQuery.getJSON() method helps load JSON-encoded data from the server using a GET HTTP request.

index.html

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title>College student data</title>
    <script type="text/javascript" src="js/jquery-1.9.1.js"></script>
    <script type="text/javascript" src="js/highcharts.js"></script>
    <script type="text/javascript">
        $(function () {
         
				var processed_json = new Array();	
				$.getJSON('http://localhost:8080/TestHttpJson/rest/json', function(data) {
		
					// Populate series
					for (i = 0; i < data.student_data.length; i++){
						processed_json.push([data.student_data[i].key, parseInt(data.student_data[i].value)]);
					}
				
				    // draw chart
					$('#container').highcharts({
					chart: {
						type: "column"
					},
					title: {
						text: "Student data"
					},
					xAxis: {
						allowDecimals: false,
						title: {
							text: "Branch of studies"
						}
					},
					yAxis: {
						title: {
							text: "Number of students"
						}
					},
					series: [{
						data: processed_json
					}]
				});	
			});
		});
    </script>
</head>
<body>
    <div id="container" style="height: 400px"></div>
</body>
</html>

Finally, open the above HTML page in the browser. If no errors occur, then you should see the following output!

output_1

output_2

In addition, one can also use the various chart types and options for better customization. Hope this helps! Thanks for visiting! 🙂

Implement Lightbox using jQuery plugin!

Hi guys!

Lightbox is a well-known JavaScript technique used to display images or any web content using modal dialogs. Not too long ago, the lightbox plugin was written in jQuery that allowed developers to modify the code and come up with new plugins that carry out the same task.

Colorbox is one such jQuery plugin that we can use to implement a lightbox. Through this post, I will try to implement a sample HTML page that displays a lightbox using the Colorbox plugin.

test.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta name="generator"
    content="HTML Tidy for HTML5 (experimental) for Windows https://github.com/w3c/tidy-html5/tree/c63cc39" />
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="" />
    <meta name="author" content="" />
    <title>LightBox Demo</title>
    <link href="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" />
    <link href="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.4.3/example1/colorbox.css" rel="stylesheet" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    <script src="https://netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.colorbox/1.4.3/jquery.colorbox.js"></script>
  </head>
  <body>
    <div class="container">
      <a href="#ShowLightBox" class="colorbox-element">Show LightBox</a>
    </div>
    <br />
    <div style="display:none">
      <div id="ShowLightBox" style="margin:0 auto;padding:10px; background:#fff;">
        <!--sample form -->
        <div class="panel panel-info">
          <div class="panel-heading">
            <div class="row">
              <div class="col-md-10">
                <h3 class="panel-title">My Form</h3>
              </div>
            </div>
          </div>
        </div>
        <div class="form-group">
        <label>Name:</label> 
        <input type="text" placeholder="Name of the customer" class="form-control" /></div>
        <div class="form-group">
        <label>Phone:</label> 
        <input type="text" placeholder="Phone of the customer" class="form-control" /></div>
        <a href="#" class="btn btn-default">Submit</a>
      </div>
    </div>
    <script>
      $(document).ready(function($) {
            $(".colorbox-element").colorbox({inline:true, width:"70%", height:"95%"});
      });   
        
</script>
  </body>
</html>

Save and open the above web page in any browser and you should see the following output!

lightbox_demo

jQuery mobile: Page loading widget

Hey everyone!

jQuery mobile provides a navigation system that can display pages with a set of animated transitions. Now, developers can add various transitions including fade, pop, flip, turn etc to their web pages. However, when you carry out a background task that consumes a lot of time, it is advisable to display a Page Loading widget. This widget handles the task of displaying the loading dialog.

Here is a short demo of the Page loading widget!

test.html


<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>

<script type="text/javascript">

function showIndicator(){
$.mobile.loading( 'show', {
	text: 'Loading...',
	textVisible: true,
	theme: 'b',
	html: ""
   });
}

function hideIndicator(){
$.mobile.loading( 'hide');
}

</script>

</head>
<body>

<input type="button" value="Click me" onclick="showIndicator();"/>
<input type="button" value="Hide me" onclick="hideIndicator();"/>

</body>
</head>

</html>

The result looks something like this,

output

Note: The page loading dialog was previously configured globally with three settings $.mobile.loadingMessage, $.mobile.loadingMessageTextVisible, and $.mobile.loadingMessageTheme which are now deprecated. In addition to the methods for showing and hiding, $.mobile.showPageLoadingMsg and $.mobile.hidePageLoadingMsg are also deprecated.

Source: jQuery mobile website