We saw in Part1 how to use AJAX with JavaScript and jQuery to get data from a MySQL database and from an XML file. In this second part you will see how it works with data stored in JSON.
Demo
I am using the same AJAX example than in Part1 but this time with JSON.
JSON
I first created a file data.json
and here is how I structured my data in it.
{
"pages": [
{
"id": 1,
"title": "Welcome",
"content": "Content coming straight from JSON."
},
{
"id": 2,
"title": "Who I Am",
"content": "Web developer having some fun with JSON."
},
{
"id": 3,
"title": "Get In Touch",
"content": "Find me on <a href='https://twitter.com/WTutorialSource'>Twitter</a>."
}
]
}
JavaScript & JSON
Now we have our JSON file with the data ready we are going to access it using JavaScript.
JavaScript
Remember that when using AJAX with JavaScript you need to create an XMLHttpRequest
object by using the getXmlHttpRequestObject()
function you can
find in Part1.
function getDataFile(pageId){
var container = document.getElementById("wrap-content");
container.innerHTML = "Loading...";
xmlHttp = getXmlHttpRequestObject();
xmlHttp.open("GET", "data.json", true);
xmlHttp.setRequestHeader("Content-type", "application/json", true);// Header to call JSON file
xmlHttp.send();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status==200) {
var result = JSON.parse(xmlHttp.responseText);
var pcontent = "";
// We loop through the values in 'pages' array stored in the JSON file
for(var obj in result.pages){
var pid = result.pages[obj].id;// We get each 'id'
if(pageId==pid){// We compere each 'id' with the value in 'pageId'
// If true we get our 'title' and 'content'
pcontent = '<b>'+ result.pages[obj].title +'</b><br />'+ result.pages[obj].content;
}
}
container.innerHTML = pcontent;
}
}
}
JQuery & JSON
And now for those interested in using jQuery rather than JavaScript this is the last chapter.
JQuery
With jQuery we are going to be using the $.getJSON
method specially made for JSON.
function getDataFile(pageid){
var container = $("#wrap-content");
if($.isNumeric(pageid)){// Make sure the sent value is nothing but a number
container.html("Loading...");
var url = "data.json";
$.getJSON(url, function (data) {
$.each(data.pages, function (index, value) {
if(pageid==value.id){
container.html('<b>'+ value.title +'</b><br />'+ value.content);
}
});
});
}else{
container.html("Don't play with the code. Thanks.");
}
}
Make sure you leave a space before or after the ‘+’ sign as I did. It must not touch the value
as I experienced problems with Firefoxe showing the error undefined
.
You did a really good job on those tutorials. Thanks