designing4u.de Yet Another Coding Blog

4Jun/080

Loading content into multiple div containers using jQuery and JSON

Because I didn't write anything in a long time and because I just changed the layout of my site, I decided to write a new example about jQuery and extend it this time with JSON. After studying google analytics I noticed that people are mostly interested in jQuery examples and specifically in showing and hiding content after users click. Because I already covered this example, I decided that this time I'll show you, how to load content into different div containers at one time. If you assume that you want to load content into more boxes, you definitely need to use JSON (JavaScript Object Notation). Of course one can say that XML would be suitable for this example as well, but the advantage of JSON is that it doesn't produce that much overhead. Of course XML is more versatile than JSON but with build in function of jQuery you can easily process received date.

After we'll be done with this example, our final solution will look more or less like that:

load content box 1,3,5
load content box 2,4

OK, let's break this code into pieces. First of all we need our HTML code, where our function can load the content. As usually, don't forget to include the jQuery library, because without nothing will really happen.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<style type="text/css">
.box1, .box2, .box3, .box4, .box5 {
	width:100px;
	height:100px;
	border:1px solid #000;
	float:left;
}
span {
	cursor:pointer;
	font-weight:bold;
}
#unload {
	color:red;
}
</style>
<span class="1,3,5">load content box 1,3,5</span><br /><span class="2,4">load content box 2,4</span>
<div class="box1"></div>
<div class="box2"></div>
<div class="box3"></div>
<div class="box4"></div>
<div class="box5"></div>

I think this code is self explanatory. Our span elements will register an on click event and display the content in according boxes. The only thing you need to know is that class attribute defines the numbers of boxes, in which our content will be displayed (our first link will display content in box1, box3 and box5, therefore the name of the class is '1,3,5'). It's also important that you keep the names of the classes with according numbers in the div containers, because this code won't work either. If you decide to change them, don't forget to change it in the jQuery function as well. Let's move to the jQuery part.

1
2
3
4
5
$(document).ready(function(){
  $('span').click(function() {
    var boxes = $(this).attr('class');
  });
});

We load our event listeners as soon as our DOM is loaded. In the first part of this code an event listener, which will be triggered whenever a user clicks on a span element. The first thing our function does is saving of the class value in variable 'boxes'.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
$(document).ready(function(){
  $('span').click(function() {
    var boxes = $(this).attr('class');
    if($(this).html() == 'unload boxes '+boxes) {
      var empty = boxes.split(',');
      for(var i=0;i<5;i++) {
        $('.box'+empty[i]).html('');
        $(this).attr('id','')
      }
      $(this).html('load content box '+boxes);
    } else {
      $.getJSON('json.php',{boxes:boxes},function(data){
        $.each(data, function(i,item){
          $(item.class).html(item.text);
        });
      });
      $(this).html('unload boxes '+boxes);
      $(this).attr('id','unload')
    }
  });
});

Full code might be a little bit tricky, therefore I'll try to explain it as good as possible. We add and if else statement. The first part of our statement will be responsible for unloading the boxes (simply removing the content out of them), the second part will do exactly the opposite. Let's start with explaining the second part first, cause that's the part, which will be executed first. We use an HTTP GET request to retrieve JSON data from an external file. In our case it will be json.php (content of this file will follow). As an addition we pass an argument boxes, which will tell our php file, for which boxes we want to load the content. After we receive the JSON data, we loop through it and paste it into according boxes. It is worth to mention in this moment that our script will receive a multi-dimensional array, in which we will save the classes of the boxes, in which we want to display our text and according texts. After our loop is done, we will replace the text of the link and add an id to give it a different color.

The first part of the script checks the text of the link, which was clicked by the user. If it contains the string, with which we replaced it, after loading of JSON data was done, we use again the class of our span attribute to remove the text from according boxes and we replace the text again.

The only thing left is the content of php file, which we used to create JSON data.

1
2
3
4
5
6
7
8
9
$array = array ();
$boxes = explode(',',$_GET['boxes']);
 
foreach($boxes as $box) {
  $push = array('class' => '.box'.$box, 'text' => 'test for box '.$box);
  array_push($array,$push);
}
 
echo json_encode($array);

In our php file we first initialize our array and we split the received data. For each value we received we extend our array adding a class name and corresponding text. In the last part we encode the array into JSON data and echo it. You can do all the magic you can imagine in this file. You can use IDs of the articles or users from your database and save it in the array. You can even extend this array and the jQuery function by extra fields.

One thing worth mentioning is that we use id attribute to change the color of our links. It is not really best practice, because multiple ids with the same name in one document wont validate with W3C rules. However, we do that on client side, therefore it shouldn't be an issue for a validation.

That's all. I hope you like this example. I know it's pretty custom and you will need to adjust it for your needs, but I hope it's clear enough for you to understand how JSON works and how to proceed retrived JSON data.

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment


No trackbacks yet.

Pages

Categories

Blogroll

Archive

Meta