1
votes

I created "omarkasec" as a function and I get car brands from database via ajax and I added at the select element this car brands as options via ajax --> success. But I can't set a value this select element.

I tried this codes for set value:

  1. $('select[name=marka]').val('Lada');
  2. $('select[name=marka] option[value=Lada]').prop('selected', true);
  3. $('select[name=marka] option[value=Lada]').attr('selected', 'selected');

this codes don't work. But if I add alert(""); in "omarkasec" function the codes do work and if I remove alert(""); the codes don't work.

<div id="marka" class="gizle" >
   Marka: <br>
   <select name="marka" onchange="omodelsec()" size="10" ></select>
</div>

<script language='javascript' type='text/javascript'>
    function omarkasec() {
        $.ajax({
            type: "POST",
            url: "aracsor.php",
            dataType: "json",
            data: {
                otomobilmodelyili : $("select[name=modelyili]").val(), //This work, because i created php.
            },
            success: function(donen){
                $("#marka").removeClass("gizle");
                $("#model").addClass("gizle");
                $("#yakit").addClass("gizle");
                $("#sanziman").addClass("gizle");
                $("#cekis").addClass("gizle");
                $("#kasatipi").addClass("gizle");
                $("select[name=marka]").empty();
                $.each(donen, function (index, otomarka) {
                    $("select[name=marka]").append($("<option>", {
                        text : otomarka,
                        value  : otomarka,
                    }));
                });
            },
        });
     //if I add here alert(""); The following code works.
    }
    </script>

<script language='javascript' type='text/javascript'>
   omarkasec();
   $('select[name=marka]').val('Lada');
   alert($('select[name=marka]').val()); //if I add alert(""); this code work but if I remove alert(""); this code get null value.
</script>
2
Try putting your code in between $( document ).ready(function() { //put code here }); You need to wait for doucment to load before finding elements and setting valuesPolynomial Proton

2 Answers

2
votes

Ajax calls are asynchronous. Your code executes the $.ajax() call passing it a call back function, but that call back function is not executed at that very moment.

The execution immediately proceeds with the statement after $.ajax() but at that moment the content has not been loaded.

However, if you perform an alert(), the call back might eventually be triggered while the alert dialog is open, and thus content is loaded by your call back function. If you then close the popup, any code following it will find the content is there.

One way to solve this, is to use the return value of the $.ajax call, which is a promise, and chain a then call to it:

function omarkasec(oncomplete) {
    return $.ajax({
//  ^^^^^^
        type: "POST",
        url: "aracsor.php",
        dataType: "json",
        data: {
            otomobilmodelyili : $("select[name=modelyili]").val(),
        },
        success: function(donen){
            $("#marka").removeClass("gizle");
            $("#model").addClass("gizle");
            $("#yakit").addClass("gizle");
            $("#sanziman").addClass("gizle");
            $("#cekis").addClass("gizle");
            $("#kasatipi").addClass("gizle");
            $("select[name=marka]").empty();
            $.each(donen, function (index, otomarka) {
                $("select[name=marka]").append($("<option>", {
                    text : otomarka,
                    value  : otomarka,
                }));
            });
        },
    });
}

// provide (anonymous) callback function to the `then` method: 
omarkasec.then(function () {
     // this code will only be executed when content is loaded:
     $('select[name=marka]').val('Lada');
     alert($('select[name=marka]').val());
});
1
votes

You have a race condition. You are calling omarkasec() and not waiting for it to finish to execute the select.val() action. When you add the alert it "works" because it gives the code some extra time to complete the ajax call an fill the values. When you alert it, the values are already filled.

All your code that depends on the result from the ajax call must be inside the success callback.