set of selected value after ajax call

I have a form in which two selects are correlated.
After selecting a value from the first, an ajax call is triggered to recover the values of the second one.
I use this form for both insert and edit of the data.
The first case is all smooth.
The edit instead doesn’t cooperate because when I try to set the selected value of the second select the operation doesn’t show anything.
Here’s the code:

HTML

<select class="inputtext" id="category" name="category" onchange="loadsub(); return false;">
    <option value="0"> -- </option>
    <?php code to load the values ?>
</select>   
<br />  
<strong>Subcategory</strong>                
<select class="inputtext" id="subcategory" name="subcategory">
    <option value="0"> -- </option>
</select>   

AJAX

function open(id, edit) {
    $('#prod').css("display", "block");
    request= 2;
    $.ajax({
        type: "POST",
        dataType: "json",
        url: "ajax/prod.php",
        data: {
            id: id,
            richiesta: request
        },
        async: true,
        success : function(data) {
            var i = 0;
            var tmp = '';

            if (data) {
                while(i<data.length) {
                    $('#category option[value="'+data[0]['categoria']+'"]').attr('selected', 'selected');
                    loadsub();
                    subcat= data[0]['subcategory'];
                    if (edit == 1) {
                        $('#categoria').attr("disabled", true);
                        $('#sottocategoria').attr("disabled", true);
                    }
                    i++;
                }               
            }
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) { 
            //alert("Status: " + textStatus);
            //alert("Error: " + errorThrown); 
        },
        complete: function () {
            $('#subcategory option[value="' + subcat + '"]').attr('selected', 'selected');
        }
    });
}


Source: ajax

Leave a Reply