programmer138200 programmer138200 - 6 months ago 20
Ajax Question

How to set value to public variable in ajax method?

I try to use result of ajax in outer of ajax method and wrote this code but get error that :

TypeError: foods is null

for (var j = 0; j <foods.obj.length; j++) {





$(document).ready(function () {
var foods = null;
$.ajax({
url: '/Train/TrianFood',
data: { Tarrif: 1 },
type: "POST",
context: this,
success: function (result) {foods = result;},
error: function () {}
});
var parentOfFood = $('#accordion1 .person-information');
for (var i = 0; i < parentOfFood.length; i++) {
var foodSelect = $(parentOfFood[i]).find('select[name$=Food]');

for (var j = 0; j <foods.obj.length; j++) {

foodSelect.append(new Option(foods.obj[j].ServiceType, foods.obj[j].ServiceTypeCode));
}
}
});


How to fix this?enter image description here

Answer

It's because loop is being execute before ajax response callback. To fix the problem create a function & execute it after ajax response.

Try following way-

$(document).ready(function () {
    var foods = null;
    $.ajax({
        url: '/Train/TrianFood',
        data: { Tarrif: 1 },
        type: "POST",
        context: this,
        success: function (result) {
            foods = result;
            foodSelectHandler();
        },
        error: function () {}
    });
    var parentOfFood = $('#accordion1 .person-information');

    function foodSelectHandler(){
        for (var i = 0; i < parentOfFood.length; i++) {
            var foodSelect = $(parentOfFood[i]).find('select[name$=Food]');

            for (var j = 0; j <foods.obj.length; j++) {

                foodSelect.append(new Option(foods.obj[j].ServiceType, foods.obj[j].ServiceTypeCode));
            }
        }
    }

});
Comments