0

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/

3
  • 5
    STOP and fix your SQL injection hole before you get your server destroyed. Commented Jan 18, 2013 at 15:53
  • can you post the recived json object? Commented Jan 18, 2013 at 15:55
  • This is result i am getting and you can see in result it has [ sign in start and at end with that i working fine. [{"subcat_id":"1","cat_id":"1","subcat_name":"Aarti Chowk"},{"subcat_id":"2","cat_id":"1","subcat_name":"Ansal Plaza"},{"subcat_id":"3","cat_id":"1","subcat_name":"Bharat Nagar"}] Commented Jan 19, 2013 at 3:31

2 Answers 2

1

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
}
));
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks it's working bro and thanks to other people too who answer this post.
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.