1

Hello I have a following html

<select id="fld_base_profile_id" defaultValue="-1" class="m-wrap span10" field="fld_base_profile_id" appEditor="true"></select>

I have this in my ajax

$result['analyze_type'][]   = array ("id" => $row[idatabase::FIELD_ID], "name" => $row[idatabase::FIELD_PROFILE_NAME]);
echo json_encode($result);

and in js part (by the way i'm using Prototype.js) :

var JSON    = transport.responseText.evalJSON();

In console, my JSON.analyze_type looks like this

Array[1]
0: Object
id: "939"
name: "Reaktif İndüktif Kontrolü Ana Profili"

The question is, how can i parse this JSON data so it can change my html like

<option value="id">name</option>  ??

EDIT: Solution:

this.baseProfile    = $("fld_base_profile_id");

var JSON    = transport.responseText.evalJSON();
    this.type   = JSON.analyze_type;
    for(var i = 0; i < JSON.analyze_type.length; i++) {
        var profile = JSON.analyze_type[i];
        var opt     = document.createElement("option");
        opt.value   = profile.id;
        opt.text    = profile.name;
        this.baseProfile.appendChild(opt);
    }
FreshPro
  • 875
  • 3
  • 14
  • 35

3 Answers3

1

Try this

var el = document.getElementById('fld_base_profile_id');

for(var i = 0; i < JSON.length; i++) {
    var profile = JSON[i],
        opt = document.createElement("option");

    opt.id = profile.id;
    opt.value = profile.name;
    el.appendChild(opt);
}​
andbas
  • 591
  • 4
  • 8
1

You could do it in a much cleaner way

Firstly make sure you are passing the Content-Type: application/json header in your JSON response - All of the Ajax methods in Prototype will automatically process the response as JSON and put it into transport.responseJSON

Then your javascript can clean up to this

this.baseProfile    = $("fld_base_profile_id");

var type = transport.responseJSON.analyze_type;

type.each(function(item){
    var option = new Element('option',{'value':item.id}).update(item.name);
    this.baseProfile.insert(option);
},this);
Geek Num 88
  • 5,264
  • 2
  • 22
  • 35
0

You can use JSON.Parse to turn the JSON you get into an object. then you can loop over the items, assign each one to an <option> object and then append them to the select.

JavaScript - populate drop down list with array explains how to create the option tags.

Community
  • 1
  • 1
Nzall
  • 3,439
  • 5
  • 29
  • 59