Mandeep Gill
Mandeep Gill

Reputation: 4907

How to get json object using php and mysql array

I am trying to get json data from php and when by using jquery json it show me undefined object. I don't know where is problem in my code. can any one help ?

Here is json code :

$("document").ready(function() {
$("body").css("background", "#ccc");
$(".sitebuttons").click(function() {
    $("#subcat").html("");
    $.getJSON("subcat.php", {catid: $(this).attr("id")}, function(data){
        $.each(data, function(index, array) {
            $("#subcat").append("<input type='button' class='subcat' id='" + data.subcat_id + "' value='"
                    + data.subcat_name + "'></p>");
        });
    });
});

});

and Here is PHP Code

 $select_subcat = mysql_query("SELECT * FROM wp_leadsubcat WHERE cat_id=" . $_GET['catid']);
$rows = array();
while ($result2 = mysql_fetch_assoc($select_subcat)) {
    $rows[] = $result2;
}
echo json_encode($rows);

Please check screenshot here : http://imageshack.us/photo/my-images/560/screenshotqvl.png/

Upvotes: 0

Views: 733

Answers (2)

macino
macino

Reputation: 457

read documentation about jquery each.

in short jQuery.each( collection, callback(indexInArray, valueOfElement) )

index means index and valueOfElement means the current element from the collection. In your case row.

here is a fix.

$("document").ready(function() {
$("body").css("background", "#ccc");
$(".sitebuttons").click(function() {
  $("#subcat").html("");
  $.getJSON("subcat.php", {catid: $(this).attr("id")}, function(data){
    $.each(data, function(index, row) {
      $("#subcat").append(
         "<input type='button' class='subcat' id='" + row.subcat_id + "' value='"+ row.subcat_name + "'>"
      );
    });
  });
});

and the append part could be optimized like this (it's more readable as you can see)

$("#subcat").append($(
  "<input/>"
, {
    cssClass: 'subcat'
  , id: row.subcat_id
  , value: row.subcat_name
}
));

Upvotes: 1

mercsen
mercsen

Reputation: 692

i think an index would solve the problem

 $("#subcat").append("<input type='button' class='subcat' id='" + data[index].subcat_id + "' value='"
                    + data[index].subcat_name + "'></p>");

Upvotes: 1

Related Questions