.demo-button{ width:90px; margin-top:20px; padding:15px; font-weight:400; background-color:rgb(175, 66, 107); color:rgba(255, 255, 255, 0.901961); text-decoration:none; text-align:center; text-shadow:rgba(0, 0, 0, 0.701961) 0px -1px 0px; border-radius:3px; box-shadow:rgba(255, 255, 255, 0.0980392) 0px 0px 0px 1px inset, rgba(255, 255, 255, 0.701961) 0px 4px 7px -4px inset, rgba(255, 255, 255, 0) 0px 56px 47px -41px inset, rgba(0, 0, 0, 0.498039) 0px 0px 8px -1px; background-image:linear-gradient(to top, rgba(0, 0, 0, 0.4), transparent); border:0; cursor:pointer } #demo-wrap-content{margin:20px 0px} #demo-wrap{text-align:center}AJAX With JavaScript And JQuery Part2 | Web Tutorial Source

AJAX With JavaScript And JQuery Part2

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.

Let’s get some data from a JSON file.

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.

One thought on “AJAX With JavaScript And JQuery Part2

Leave a Reply

Your email address will not be published. Required fields are marked *

function getDataFile(pageid){ var container = jQuery("#demo-wrap-content"); if(jQuery.isNumeric(pageid)){ container.html("Loading..."); var url = "/assets/tutorials/ajaxwithjavascriptandjquerypart2/data.json"; jQuery.getJSON(url, function (data) { jQuery.each(data.pages, function (index, value) { if(pageid==value.id){container.html(''+ value.title +'
'+ value.content);} }); }); }else{ container.html("Please, if you want to play with the code do it on your machine. Thanks."); } }