Jump to content

need some help with JSON /JQuery


webguync

Recommended Posts

Hi, I am working on a project to help me learn more about JSON and JQuery and how they interact. I am able to pull in my JSON data fine and it displays in an HTML table. What isn't working is I want the tables rows to be striped, and normally this works, but I didn't know if it isn't working b/c it is AJAX or if I have something wrong with my JQuery. Also, I was hoping to add a reference to an image path in the JSON file as well, but wasn't sure how that is done or if it could be done at the JSON level.

 

Here is my code that I am working on:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>JSON Presidents</title>
	<style type="text/css">
        
        body{
            font-family:arial, helvetica, sans-serif;
        text-align:center;
            width:100%;
            margin:200px 0 0 0;
        }
        
	#PresidentInfo{
	width:75%;
	margin:0 auto;
       
        
	}
        
        table#data{
            width:100%;
        }
        
        table#data th{
            background:#333;
            color:#fff;
            text-align:center;
            text-shadow:1px 1px 1px rgba(0,0,0,1);
            padding:5px;
        }
        
        table#data td{
            border:1px solid #333;
            border-collapse:collapse;
            padding:10px;
            margin:0 5px 0 5px;
            text-align:center;
        }
        
        .odd {
   background: #ccc;
}
            
	

	
	
	</style>
</head>
<body>
        
    <div id="PresidentInfo">
  
    </div>

    <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
	   <script>
           (function ($) {
$(document).ready (function(){
   $("tr:odd").addClass("odd");
    });
});
})(jQuery);
</script>
    <script>
  $.getJSON('data.json', function(data) {
        var output="<table id='data'><tr><th>First Name:</th><th>Last Name:</th><th>Month of Inauguration:</th><th>Year of Inauguration:</th></tr>";
        for (var i in data.Presidents) {
            output+="<tr><td>" + data.Presidents[i].firstName + "</td><td>" + data.Presidents[i].lastName + "</td><td>" + data.Presidents[i].YearInauguratedPresident.month +  "</td><td>" + data.Presidents[i].YearInauguratedPresident.year + "</td></tr>";
        }

        output+="</tr></table>";
        document.getElementById("PresidentInfo").innerHTML=output;
  });
    </script>
 
</body>
</html>
{"Presidents":[
        {
            "firstName":"Barack",
            "lastName":"Obama",
            "YearInauguratedPresident": {
                "month":"January",
                "day":20,
                "year":2009
            }
        },
        {
            "firstName":"George W",
            "lastName":"Bush",
            "YearInauguratedPresident": {
                "month":"January",
                "day":20,
                "year":2001
				}
            },
			     {
            "firstName":"Bill",
            "lastName":"Clinton",
            "YearInauguratedPresident": {
                "month":"January",
                "day":20,
                "year":1993
				}
            },
			     {
            "firstName":"George",
            "lastName":"H.W Bush",
            "YearInauguratedPresident": {
                "month":"January",
                "day":20,
                "year":1989
            }
        }
]}
Link to comment
Share on other sites

Because you first apply the 'odd' class to nothing upon domready (the table isn't created yet), and then retrieve the json and populate the table. Apply the odd class after you retrieve the json/create the table.

 

also you can write this javascript:

document.getElementById("PresidentInfo").innerHTML=output;

with jQuery:

$('#PresidentInfo').html(output);
Link to comment
Share on other sites

just assign the css selector to .add class, then add the class to #presidentInfo:

 

example:

 

1. CSS

.odd tr:nth-child(odd) {
           background-color: #ccc;
           }

2. All jquery script ( no need extra code )

        <script>

            $.getJSON('data.json', function(data) {
                var output = "<table id='data'><tr><th>First Name:</th><th>Last Name:</th><th>Month of Inauguration:</th><th>Year of Inauguration:</th></tr>";
                for (var i in data.Presidents) {
                    output += "<tr><td>" + data.Presidents[i].firstName + "</td><td>" + data.Presidents[i].lastName + "</td><td>" + data.Presidents[i].YearInauguratedPresident.month + "</td><td>" + data.Presidents[i].YearInauguratedPresident.year + "</td></tr>";
                }

                output += "</tr></table>";
                $('#PresidentInfo').html(output).addClass("odd");
            });
        </script>

 

Because you first apply the 'odd' class to nothing upon domready (the table isn't created yet), and then retrieve the json and populate the table. Apply the odd class after you retrieve the json/create the table.

 

 

Description: Specify a function to execute when the DOM is fully loaded.

 

@CroNiX, according the docs, this (.ready) function/method will be executed after the DOM is done.

Edited by jazzman1
Link to comment
Share on other sites

just assign the css selector to .add class, then add the class to #presidentInfo:

 

example:

 

1. CSS

.odd tr:nth-child(odd) {
           background-color: #ccc;
           }

2. All jquery script ( no need extra code )

        <script>

            $.getJSON('data.json', function(data) {
                var output = "<table id='data'><tr><th>First Name:</th><th>Last Name:</th><th>Month of Inauguration:</th><th>Year of Inauguration:</th></tr>";
                for (var i in data.Presidents) {
                    output += "<tr><td>" + data.Presidents[i].firstName + "</td><td>" + data.Presidents[i].lastName + "</td><td>" + data.Presidents[i].YearInauguratedPresident.month + "</td><td>" + data.Presidents[i].YearInauguratedPresident.year + "</td></tr>";
                }

                output += "</tr></table>";
                $('#PresidentInfo').html(output).addClass("odd");
            });
        </script>

@CroNiX, according the docs, this (.ready) function/method will be executed after the DOM is done.

right, but when the dom is ready his ajax call hasn't fired yet.

Link to comment
Share on other sites

 

right, but when the dom is ready his ajax call hasn't fired yet.

 No. Ajax call should be executed by javascript and all requested data will be probably parsed from the web browser before </body></html> are being loaded in to DOM. So, when the content will be returned back from the server and loaded in to DOM is a different story :) That's why, we should be always using callback functions while dealing with ajax ( especially with large data, databases, another servers and so on ) just to make sure that all data is successfully retrieved and loaded in to DOM before any rest of data to be parsed of the browser.

Edited by jazzman1
Link to comment
Share on other sites

It isn't. Try it. DOM ready means the DOM (structure) is loaded into the browser, not when all javascript is executed.

 

It works if you put the $("tr:odd").addClass("odd"); as the last line of the getJSON callback function where he is creating the table.

Link to comment
Share on other sites

Maybe, you don't understand me very well ;) I've never said that JS or Ajax are part of DOM. No, they aren't, but the content that they created/retrieved will be loaded into DOM in very specific order in the HTML document.

 

It works if you put the $("tr:odd").addClass("odd"); as the last line of the getJSON callback function where he is creating the table.

His script loads lots of javascript errors into firebird, I will try later, but mine works fine.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>JSON Presidents</title>
         <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
        
        <style type="text/css">

            body{
                font-family:arial, helvetica, sans-serif;
                text-align:center;
                width:100%;
                margin:200px 0 0 0;
            }

            #PresidentInfo{
                width:75%;
                margin:0 auto;


            }

            table#data{
                width:100%;
            }

            table#data th{
                background:#333;
                color:#fff;
                text-align:center;
                text-shadow:1px 1px 1px rgba(0,0,0,1);
                padding:5px;
            }

            table#data td{
                border:1px solid #333;
                border-collapse:collapse;
                padding:10px;
                margin:0 5px 0 5px;
                text-align:center;
            }

           .odd tr:nth-child(odd) {
           background-color: #ccc;
           }
        </style>
    </head>
    <body>
        <div id="PresidentInfo"></div>
        <script type="text/javascript">
            jQuery.getJSON('data.json', function(data) {
                var output = "<table id='data'><tr><th>First Name:</th><th>Last Name:</th><th>Month of Inauguration:</th><th>Year of Inauguration:</th></tr>";
                for (var i in data.Presidents) {
                    output += "<tr><td>" + data.Presidents[i].firstName + "</td><td>" + data.Presidents[i].lastName + "</td><td>" + data.Presidents[i].YearInauguratedPresident.month + "</td><td>" + data.Presidents[i].YearInauguratedPresident.year + "</td></tr>";
                }

                output += "</tr></table>";
                $('#PresidentInfo').html(output).addClass("odd");
            });
        </script>
    </body>
</html>
Edited by jazzman1
Link to comment
Share on other sites

Here's my testing:

 

1. Using .ready method at top of the document - works !

Note, that .add class is added to #presidentinfo before entire html to be loaded.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>JSON Presidents</title>
        
         <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
         
         <script type="text/javascript">    
         $(document).ready(function() {
           $('#PresidentInfo').addClass("odd"); 
         });
         </script>
        <style type="text/css">

            body{
                font-family:arial, helvetica, sans-serif;
                text-align:center;
                width:100%;
                margin:200px 0 0 0;
            }

            #PresidentInfo{
                width:75%;
                margin:0 auto;


            }

            table#data{
                width:100%;
            }

            table#data th{
                background:#333;
                color:#fff;
                text-align:center;
                text-shadow:1px 1px 1px rgba(0,0,0,1);
                padding:5px;
            }

            table#data td{
                border:1px solid #333;
                border-collapse:collapse;
                padding:10px;
                margin:0 5px 0 5px;
                text-align:center;
            }

           .odd tr:nth-child(odd) {
           background-color: #ccc;
           }
        </style>
    </head>
    <body>
        <div id="PresidentInfo"></div>
        <script type="text/javascript">
            jQuery.getJSON('data.json', function(data) {
                var output = "<table id='data'><tr><th>First Name:</th><th>Last Name:</th><th>Month of Inauguration:</th><th>Year of Inauguration:</th></tr>";
                for (var i in data.Presidents) {
                    output += "<tr><td>" + data.Presidents[i].firstName + "</td><td>" + data.Presidents[i].lastName + "</td><td>" + data.Presidents[i].YearInauguratedPresident.month + "</td><td>" + data.Presidents[i].YearInauguratedPresident.year + "</td></tr>";
                }

                output += "</tr></table>";
                $('#PresidentInfo').html(output);
            });
        </script>

    </body>
</html>

2. Not-working method using self-executing jquery function before html to be loaded and json method called.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>JSON Presidents</title>
        
         <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
         
    <script type="text/javascript">
 /*
$(document).ready(function() {
           $('#PresidentInfo').addClass("odd"); 
         }); 
*/
    
// self executing function here
(function() {
  $('#PresidentInfo').addClass("odd"); 
})();
         </script>
        <style type="text/css">

            body{
                font-family:arial, helvetica, sans-serif;
                text-align:center;
                width:100%;
                margin:200px 0 0 0;
            }

            #PresidentInfo{
                width:75%;
                margin:0 auto;


            }

            table#data{
                width:100%;
            }

            table#data th{
                background:#333;
                color:#fff;
                text-align:center;
                text-shadow:1px 1px 1px rgba(0,0,0,1);
                padding:5px;
            }

            table#data td{
                border:1px solid #333;
                border-collapse:collapse;
                padding:10px;
                margin:0 5px 0 5px;
                text-align:center;
            }

           .odd tr:nth-child(odd) {
           background-color: #ccc;
           }
        </style>
    </head>
    <body>
        <div id="PresidentInfo"></div>
        <script type="text/javascript">
            jQuery.getJSON('data.json', function(data) {
                var output = "<table id='data'><tr><th>First Name:</th><th>Last Name:</th><th>Month of Inauguration:</th><th>Year of Inauguration:</th></tr>";
                for (var i in data.Presidents) {
                    output += "<tr><td>" + data.Presidents[i].firstName + "</td><td>" + data.Presidents[i].lastName + "</td><td>" + data.Presidents[i].YearInauguratedPresident.month + "</td><td>" + data.Presidents[i].YearInauguratedPresident.year + "</td></tr>";
                }

                output += "</tr></table>";
                $('#PresidentInfo').html(output);
            });
        </script>

    </body>
</html>

3. Call self-executing function after json method and div#presidentinfo - works!

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title>JSON Presidents</title>

        <script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

        <style type="text/css">

            body{
                font-family:arial, helvetica, sans-serif;
                text-align:center;
                width:100%;
                margin:200px 0 0 0;
            }

            #PresidentInfo{
                width:75%;
                margin:0 auto;


            }

            table#data{
                width:100%;
            }

            table#data th{
                background:#333;
                color:#fff;
                text-align:center;
                text-shadow:1px 1px 1px rgba(0,0,0,1);
                padding:5px;
            }

            table#data td{
                border:1px solid #333;
                border-collapse:collapse;
                padding:10px;
                margin:0 5px 0 5px;
                text-align:center;
            }

            .odd tr:nth-child(odd) {
                background-color: #ccc;
            }
        </style>
    </head>
    <body>
        <div id="PresidentInfo"></div>
        <script type="text/javascript">
            jQuery.getJSON('data.json', function(data) {
                var output = "<table id='data'><tr><th>First Name:</th><th>Last Name:</th><th>Month of Inauguration:</th><th>Year of Inauguration:</th></tr>";
                for (var i in data.Presidents) {
                    output += "<tr><td>" + data.Presidents[i].firstName + "</td><td>" + data.Presidents[i].lastName + "</td><td>" + data.Presidents[i].YearInauguratedPresident.month + "</td><td>" + data.Presidents[i].YearInauguratedPresident.year + "</td></tr>";
                }

                output += "</tr></table>";
                $('#PresidentInfo').html(output);
            });
        </script>
        <script type="text/javascript">
// self executing function here
            (function() {
                $('#PresidentInfo').addClass("odd");
            })();
        </script>
    </body>
</html>

So, what is your conclusion?

Edited by jazzman1
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.