Load Content Using JSON - Exercise

Contact Us or call 1-877-932-8228
Load Content Using JSON - Exercise

Load Content Using JSON

Duration: 20 to 30 minutes.

Open ClassFiles\jqy-ajax\Exercises\index.html in your browser. Your task is to show the user details about the special for a given day when the user selects a day from the select drop-down.

  1. Append a target div after the form that's inside the #specials element; this will be where you put information about the special once you receive it.
  2. Bind to the change event of the select element; when the user changes the selection, send an Ajax request to ClassFiles\jqy-ajax\Exercises\data\specials.json.
  3. When the request returns a response, use the value the user selected in the select (hint:$.fn.val) to look up information about the special in the JSON response.
  4. Add some HTML about the special to the target div you created.
  5. Finally, because the form is now Ajax-enabled, remove the submit button from the form.

Note that we're loading the JSON every time the user changes their selection. How could we change the code so we only make the request once, and then use a cached response when the user changes their choice in the select?

Solution:

jqy-ajax/Solutions/js/specials.js
$(document).ready(function() {
	var $sel = $('#specials select[name=day]');
	var $content = $('<div />').insertAfter('#specials form');
	$sel.change(function(e) {
		var day = $(this).val();
		if (day.length) {
			$.ajax('data/specials.json', {
				dataType:'json',
				success: function(data) {
					var special = data[day];
					if (special) {
						$content
							.empty()
							.append($('<h1>' + special.title + '</h1>')
								.css('color', special.color))
							.append('<img src="' + special.image + '" />' +
											'<p>' + special.text + '</p>');
					}
				}
			});
		} else {
			$content.empty();
		}
	});
	$('#specials li.buttons').remove();
});

Each time a response is received, we empty out the new div and create content from the incoming JSON. The day name from the select's value is used to select one item from the specials object.

Challenge Solution:

jqy-ajax/Solutions/js/specials-cache.js
$(document).ready(function() {
	var $specials = $('#specials');
	$specials.find('li.buttons').remove();

	var cachedResponse = null;

	var $details = $('<div/>').appendTo($specials);

	var handleResponse = function(specials, val) {
		var daySpecial = specials[val];

		var html = '<h3>' + daySpecial.title + '</h3>';
		html += '<p>' + daySpecial.text + '</p>';

		$details.html(html);
		$('<img/>')
			.attr('src', daySpecial.image)
			.appendTo($details);

		$details.css('color', daySpecial.color);
	};

	var $select = $specials.find('select')
		.change(function() {
			var val = $select.val();
			if (!val) { 
				$details.empty();
				return; 
			}

			if (cachedResponse) {
				handleResponse(cachedResponse, val);
			} else {
				$.ajax({
					type : 'get',
					dataType : 'json',
					url : 'data/specials.json',
					success : function(specials) {
						cachedResponse = specials;
						handleResponse(specials, val);
					}
				});

			}
		});
});

The handling of the response has been split off into a standalone function, handleResponse, so that we can invoke it from several places. We also created a variable to hold the response data object.

When the select changes, we look to see if the response data object has been populated, and, if so, use it by invoking handleResponse. If it isn't there, then we make the Ajax call, and use handleResponse in our callback.

Next