In this code I'm fetching selected value from the php file and assign it, but it doesn't work every time. Suppose if I refresh it then one value may be assigned and the other one is may be not, sometimes both are not assigned. What is the problem? The selectedcaste.php returns the following:
{"cast":"BC","busrout":"B20"}
For testing purposes I hardcoded it but I face the same problem.
$.ajax({url:"phpajax/selectedcaste.php",success:function(result){
var valoresArea=result; // it has the multiple values to set, separated by comma
var obj = jQuery.parseJSON(valoresArea);
$('#caste').val(obj.cast).attr("selected", "selected");
$('#route').val(obj.busrout).attr("selected", "selected");
//$('#caste').select2("val",obj.cast);
//$('#route').select2("val",obj.busrout);
}});
here my full java script
$(function(){
// for loading caste list from database at run time
var items="";
$.getJSON("phpajax/caste.php",function(data){
$.each(data,function(index,item)
{
items+="<option value='"+item.Name+"'>"+item.Name+"</option>";
});
$("#caste").html(items);
});
// for loading route list from database at run time
var items2="";
$.getJSON("phpajax/route.php",function(data){
$.each(data,function(index,item)
{
items2+="<option value='"+item.Name+"'>"+item.Name+"</option>";
});
$("#route").html(items2);
});
// assign selected value from records
$.ajax({url:"phpajax/selectedcaste.php",success:function(result){
var valoresArea=result; // it has the multiple values to set, separated by comma
var obj = jQuery.parseJSON(valoresArea);
$('#caste').val($.trim(obj.cast)).attr("selected", "selected");
$('#route').val($.trim(obj.busrout)).attr("selected", "selected");
//$('#caste').select2("val",obj.cast);
//$('#route').select2("val",obj.busrout);
}});
});
my html
<select name="caste" id="caste" style="width: 100%;">
<!-- <option value="0" selected="selected" >Choose an option...</option>-->
</select>
<select name="route" id="route" style="width:100%;">
</select>
error
some time select correctly. some time select onely one. some time both are not selected. if i use alert statement it every time it alert correctly but not select properly. i am using bootstrap 2.0 theme. thanks