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

3 Answers 3

2

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

3 Comments

Thanks a lot! I made some modifications based on your code and it works like a charm
Nice to hear, please let me know if the code have any mistakes, I'll fix it.
Sorry, that is my fault. I didn't notice that analyze_type is root object of your json.
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);

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.