0

how can we display JSON data from js to html

here is the code i have tried

<script>
$.ajax({
    url:'load_categories.php',
    type:'get',
    data:{'from':loaded,'to':loadmore},
    success: function (res) {
        var categories = $.parseJSON(res);
      var i=0;
      for (var x in categories){
          alert(categories.date_+i);
           $('#categories').append('<div>'+(categories.date_+i+'</div>'); //not displaying on html
          i++;
      }
        $('#loadmore').attr('num_loaded',(loaded+10));
    }
});
</script>

<div id="categories"></div>

<?php
//load_categories.php
$res = mysql_query("SELECT * FROM impressions LIMIT $from,$to");
//echo "SELECT * FROM impressions LIMIT $from,$to";
$arr = array();
$i= 0;
while($row = mysql_fetch_array($res)) {

    $arr['rec_id_'.$i] = $row['rec_id'];
    $arr['date_'.$i]   = $row['date'];
    $i++;
}
echo json_encode($arr);

where im doing wrong...

i think something wrong with this categories.date_+i, how can we add 0,1,2,...

3
  • what the alert(categories.date_+i); tells Commented Aug 18, 2014 at 7:51
  • 1
    You have a stray (: $('#categories').append('<div>'+(categories.date_+i+'</div>'); Commented Aug 18, 2014 at 7:52
  • Check my answer , I've update it , you can use same fields name's from database in javascript json Commented Aug 18, 2014 at 7:58

1 Answer 1

1

I've fixed your code please five it a try

The correct Code :

<script>
$.ajax({
    url:'load_categories.php',
    type:'get',
    data:{'from':loaded,'to':loadmore},
    success: function (res) {
        var categories = $.parseJSON(res);

    for(var i=0;i< categories.length;i++)
     { 

         var row = categories[i];

          alert(row.date);
         $('#categories').append('<div>'+row.date+'</div>'); //not displaying on html

      }
        $('#loadmore').attr('num_loaded',(loaded+10));
    }
});
</script>

<div id="categories"></div>

<?php
//load_categories.php
$res = mysql_query("SELECT * FROM impressions LIMIT $from,$to");
//echo "SELECT * FROM impressions LIMIT $from,$to";
$arr = array();
while($row = mysql_fetch_array($res)) {

    $arr[] = row;
}
echo json_encode($arr);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.