简体   繁体   中英

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/

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>");

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
}
));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM