HPWD
HPWD

Reputation: 2240

jQuery/JavaScript looping over json data results

I have a form where a user can select an item from a mult-select select box (A). If the item is not listed, the user can add it from another input text box (B). The value entered in (B) will perform an ajax call which will save the item to the database. After saving the item, a json object is created which then needs to populate (A) with the updated list. I have all of this working with the optionss. I now need to include if the save process passed or failed. If the process passed, then I need to include the options but if it failed, I just need the failed status. Here is what I came up with:

{
    "process": [{
        "status":"pass" ,
        "message":"The Contributors list has been refreshed to contain the entry you just saved." }
    ],
    "newoptions": [
        {"optionValue":"Item 1" , "optionDisplay":"Item 1"},
        {"optionValue":"Item 2" , "optionDisplay":"Item 2" },
        {"optionValue":"Item 3" , "optionDisplay":"Item 3" }
    ]    
}

and this is what I'm using in my .ajax routine:

success: function(j){
    if (j.process.status == 'pass'){
        var options = '';
        for (var i = 0; i < j.newoptions.length; i++) 
            {
                options += '<option value="' + j.newoptions[i].optionValue + '">' + j.newoptions[i].optionDisplay + '</option>';
            }
        $('#misc_userID').val('');  // reset value back to null 
        $("#misc_userID").effect("transfer", { to: $("#group_misc_available") }, 500);  //visual showing item added to select
        $('#group_misc_available').html(options);
    }
    else if (j.status == 'fail'){
        alert(j.process.message);   
    }
}

I'm not getting an error but it isn't processing j.process.status either so the select list (A) isn't being refreshed..

Upvotes: 2

Views: 1063

Answers (2)

Sushanth --
Sushanth --

Reputation: 55740

You are not accessing your json data properly. Try this

if (j.process[0].status == 'pass'){

Upvotes: 3

Adil
Adil

Reputation: 148110

You have array of process so need to access it with index

if (j.process.status == 'pass'){

Would be

if (j.process[0].status == 'pass'){

Upvotes: 3

Related Questions