i want define a variable in Json callback.
Code;
$("select").change(function () {
var $variable = "";
$("select option:selected").each(function () {
$variable += $(this).text() + " ";
});
$("div.yaz").text($variable);
$('#result').html('loading...');
$.getJSON('program-bilgileri.php', function(JSON){
$('#result').empty();
$.each(JSON.$variable, function(i, program){
$('#result')
.append(program.isim +'<br />')
.append(program.bilgi+'<br />')
.append(program.adres+'<hr />');
});
});
})
.trigger('change');
program-bilgileri.php returns;
{
"programlar":[
{
"isim":"Zone Alarm",
"bilgi":"bilgisayarın güvenliğini sağlar",
"adres":"www.zonealarm.com"
},
{
"isim":"Opera",
"bilgi":"güvenli ve hızlı bir web tarayıcısıdır",
"adres":"www.opera.com"
},
{
"isim":"Photoshop",
"bilgi":"güçlü bir imaj işleme yazılımıdır",
"adres":"www.adobe.com"
}
]
}
The problem is here “$.each(JSON.$variable, function(i, program)” if I define $variable in JSON it isn’t working.
Any idea?
The problems i see are
changeevent you are using$("select option:selected")which finds allselectelements in the page, and not the changed one only.use
$(this).children('option:selected')instead.selectelement and that is why you are doing+=with the$variable.. (you are also adding a space at the end). That means, though, that the variable will be something like"programlar "or"programlar somethingelse".Your returned JSON though has a key of
programlar. A single word, no spaces.. so when you doJSON[$variable]which is the correct way to access an element based on the name in a variable, it does not match.If the
<select>element does not allow multiple selection then the solution isIf indeed it is a multiselect and each option can appear in the JSON then you must check for each option found in the variable.