Archivi tag: nivo slider

Read JSON data with AjaX request

Giorgio Bongiorni

Telecommunication Engineer with more than 5 years experience in web development and SEO campaigns. Favourite languages are HTML5, PHP5, MySql, CSS3 and jQuery.

Latest posts by Giorgio Bongiorni (see all)

JSON (JavaScript Object Notation) is a lightweight data-interchange format. It’s text-based and simpler than other languages, this is the reason why it has become very popular in the last period. In this article, we’ll see how to get data from a JSON file (via AjaX requests) and dinamically fill sections of a HTML file with information read from it. Our focus will be on the technique used to retrieve and display data, so layout will be very simple (say, ugly!) but it can be easily improved with some additional CSS.

Define HTML structure

The first step is to define the HTML file. This file is basically composed of an empty section having a unique id. This id will be used to retrieve data from JSON file and poulate section with a title, an image gallery and a paragraph containing some information. Here you can find the described HTML code.

<section id="animals"></section>

Setup JSON files

The second step is to create a JSON file containing data. As stated into JSON official website, a JSON file can contain either a collection of name/value pairs or an ordered list of values (array). In our case, we will define both of them. The following snippet is composed of a “title” and a “description” as name/value element, and a “images” element as an array.

{
  "item": {
    "title": "ANIMALS",
    "description": "Lorem ipsum dolor sit amet, consectetur adipiscing 
    elit. Suspendisse vitae turpis in turpis vehicula pharetra.
    Praesent euismod elit vel dui convallis fringilla. Cras volutpat,
    eros id pellentesque posuere, odio libero dapibus dolor, at
    interdum augue risus a mi. Curabitur ultricies cursus risus in
    tincidunt. Praesent fringilla interdum pellentesque. Maecenas nec
    vulputate arcu, at pharetra erat. Integer fringilla magna at
    ornare ornare. Aliquam quis tellus sed metus porttitor convallis
    et sit amet quam.",
    "images": [
      "images/animals/puppy.jpg",
      "images/animals/beagle.jpg",
      "images/animals/bernese.jpg",
      "images/animals/labrador.jpg"
    ]
  }
}

This file will be named “animals.json”, to allow jQuery code described in the next section to fill in HTML section with the proper data.

Add jQuery code

The final step is to create a jQuery script to read data from JSON file and populate HTML section. The script has a main cicle over all sections of HTML file (this means that if you want to add another section, you can simply add it to your HTML code, choose a unique id and create a new JSON file with the same name. That’s it!). For each section, script gets the id attribute to retrieve JSON filename. Then, it makes AjaX request to open JSON file and read data. Information are formatted as key/value pairs and can simply be accessed using the “title”, “description” and “images” identifiers. Images are used to build a Nivo Slider gallery, which is started at the end of the script.

$(document).ready(function()
{
	var dir = 'data/';
	var extension = '.json';

	$('section').each(function(index) 
	{
		var item = $(this);
		var id = $(this).attr('id');
		var filename = dir + id + extension;

		// create basic structure
		item.html('<h1></h1><div class="theme-default"><div class="nivoSlider"></div></div><p></p>');

		// read data from json file (function is invoked on file read completion)
		$.getJSON(filename, function(data) 
		{
			// retrieve values from file data
			$.each(data, function(key, val) 
			{
				// title
				var title = $('#' + id + ' h1');
				title.html(val.title);

				// images
				var slider = $('#' + id + ' .nivoSlider');
				$.each(val.images, function(imageID, image) 
				{
					slider.append('<img src="' + image +'"/>');
				});
				slider.nivoSlider();

				// description
				var description = $('#' + id + ' p');
				description.html(val.description);
			});
		});
	});
});

Conclusions and downloads

We are done! Here you can find the complete code of this example. Feel free to download and use it as you want. If you have any question or doubt, ask it into comments section. Thanks!

Download the full example code!