Friso van Dijk
Friso van Dijk

Reputation: 669

Creating dynamic div content with jquery

I'm looking to put a div on my website where the content changes based on what link is clicked without refreshing. The content to put there comes from a MySQL database and it's put in JSON. My problem is that I can't get the JSON data to display when clicking the links.

Here's the script I'm using:

$(document).ready(function () {
   $.getJSON("jsondata.php",rightSideData);
   function rightSideData(data) {
      for(var i=0; i<data.length;i++) {
         $("#changetext"+data[i].id).click(function() {
            $("#rightside").html("<h1>" + data[i].title + "</h1><p />" + data[i].content);
         });
      }
   }
});

This is the div element that has to change:

<div class='rightside' id='rightside'>Test</div>

The links are constructed this way:

echo "<a id='changetext" . $row['id'] . "'> ";
echo "<div class='tile'>";
echo "<h2>Tile</h2></div></a>";

I've tested the different elements and they work fine (changing the divs content with hardcoded data, displaying the JSON data), but I'm having a hard time figuring out why the combined thing isn't working.

Upvotes: 5

Views: 806

Answers (2)

adeneo
adeneo

Reputation: 318182

Objects does'nt have a length, use $.each to iterate it instead, unless it's actually an array containing objects :

$(document).ready(function () {
   $.getJSON("jsondata.php",rightSideData);

   function rightSideData(data) {
      $.each(data, function(i, d) {
         $("#changetext" + d.id).on('click', function() {
             var h1 = $('<h1 />', {text : d.title}),
                 p  = $('<p />', {text : d.content});
             $("#rightside").html(h1.add(p));
         });
      });
   }
});

Upvotes: 3

Claudio Redi
Claudio Redi

Reputation: 68400

The problem is that i var will be data.length at the end of the loop and that's what the click handler will see.

Upvotes: 2

Related Questions