Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating dynamic div content with jquery

Tags:

json

jquery

php

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.

like image 782
Friso van Dijk Avatar asked May 15 '13 12:05

Friso van Dijk


2 Answers

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));
         });
      });
   }
});
like image 134
adeneo Avatar answered Sep 25 '22 14:09

adeneo


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.

like image 45
Claudio Redi Avatar answered Sep 25 '22 14:09

Claudio Redi