-6

I populate my departmentName in an array using ajax. during the $.each the departmentName has a value but after end of ajax when I log the departmentName it doesn't have a value.

      $("#Search").click(function () {
            var titleId = $("#title").val();
            var departmentGenericId = $("#department").val();
            var startDate = $("#startDate").val();
            var endDate = $("#endDate").val();

            var departmentName = [];
            var complianceValue = [];
            var nonComplianceValue = [];
            var complianceRate = [];
            $.ajax({
                type: "GET",
                contentType: "application/json; charset=utf-8",
                url: '/AcknowledgementAdminLevel/AcknowledgemetnComplianceRate/',
                data: {"titleId": titleId, 
                    "departmentGenericId" : departmentGenericId, 
                    "startDate" : startDate,
                    "endDate" : endDate
                },
                dataType: "json",
                success: function (data) {                                       
                    $.each(data, function () {                            
                        departmentName.push(this.DepartmentName);
                        complianceValue.push(this.Compliance);
                        nonComplianceValue.push(this.NonCompliance);
                        complianceRate.push(this.ComplianceRate);                            
                    });
                }                   
            });               
            console.log(departmentName);               
        });       
RAM
  • 91
  • 1
  • 10

1 Answers1

0

The ajax call is being called asynchronously, therefore departmentName will not have been populated when the console.log statement is executed. You can set the ajax call to perform synchronously if you really want to by adding the async option as follows:

$.ajax({
        async: false,
        //...

to the options. The ajax call will then wait for the response before proceeding execution.

DavidWainwright
  • 2,647
  • 1
  • 24
  • 29
  • Why answer when long before that we linked to proper QA while voting to close ? BTW this is a bad answer, don't recommend sync requests. – Denys Séguret Sep 10 '13 at 11:58
  • 1
    I answered because he asked, and I'm well aware it's bad practice to use sync requests, hence 'You can set the ajax call to perform synchronously *if you really want to*' - wind your neck in - I'd hate SO to become like the perl community. – DavidWainwright Sep 10 '13 at 12:27