jquery - Populate a dropdown list based on the another dropdown list using AJAX JSON -
i know question has been asked many before not exact solution resembles question.
i have dropdown list called category , dropdown rather sub 1 called grade. select category(lets select tv out of radio,washing machines,dvd players etc.), corresponding grades category(lets tv - sony, hitachi, samsung, philips..) should populate on grade dropdown. both categories , grades being fetched database , queries working perfectly.
ajax:-
<script> function getgradedetails(category){ if(category!==""){ var request = $.ajax({ url: "../controller/sales.php", type: "post", data: {category:category,action:'get_grade_details'}, datatype: "json" }); request.done(function(json_return){ //alert(json_return['grade_desc']); $( "#grade" ).append( "<option>"+json_return['grade_desc'] </option>" ); }); request.fail(function(jqxhr, textstatus) { alert( "request failed: " + textstatus ); return false; }); } else{ $("#grade").append('<option></option>'); } } </script>
html:-
<td>category <select name="category" id="category" onchange="getgradedetails(this.value)"> <option></option> <?php require_once '../model/sales.php'; @$result=sales::getallcategories(); while($value= mysql_fetch_assoc($result)){ ?> <option value="<?php echo $value['category_code']; ?>"> <?php echo $value['category_desc'] ?> </option> <?php } ?> </select> </td> <td>grade <td> <select id="grade"> </select> </td>
controller:-
<?php require_once '../model/sales.php'; $action=$_request['action']; switch($action){ case 'get_grade_details': getgradedetails(); break; default : break; } function getgradedetails(){ $category=$_post['category']; require_once '../model/sales.php'; $obj=new sales(); $result=mysql_fetch_assoc($obj->getgradesforcategory($category)); echo json_encode($result); exit; } ?>
according code, dropdown value on grade first value db. eg:-only sony, , avoids others-hitachi,samsung etc.. , change on category(eg:-washing machines), grade dropdown has values sony(tv grade),lg(washing machines grade).
what want is:-
1) values should appear whole not first/single value db.
2) change on category(tv washing machines), values relating tv should not appear(sony) , values pertaining washing machines(lg) should appear.
the problem not looping , adding items on response list options of select tag
request.done(function(json_return){ //alert(json_return['grade_desc']); **$( "#grade" ).append( "<option>"+json_return['grade_desc']</option>"** ); });
the highlighted portion should corrected values being added options, like
var options = ''; (i=0;i< json_return['grade_desc'].length;i++){ options += "<option>"+json_return['grade_desc'][i]+"</option>"; } $("#grade").append(options);
the second question needs more information. please post snippet of response ajax.
Comments
Post a Comment