Problem where Jquery .ajax function returns object after it has already skipped to the next line of code

This happens because at the moment when you are trying to use machineDetails ajax call has not yet been completed. You should wait for result and then run your code. One of the solutions is as follows:

var machineDetails=[];
        function getMachineDetails(SelectedMachine) {
            var urlMachines = '@Url.ActionLink("GetMachineDetails", "Home")';
            return $.ajax({  // <== return jqXHR object
                type: 'GET',
                url: urlMachines,
                contentType: 'application/json; charset=utf-8',
                data: { SelectedMachine : SelectedMachine} ,
                dataType: 'json',
                crossDomain: true
            });

        }
        $('#SelectMachines').change(function () {

            removeAllChildren('MachineDetailsDisplay');
            var SelectedMachine = $('#SelectMachines option:selected');
            getMachineDetails(SelectedMachine[0].value)
            .done(function(data) { // <== execute your code when ajax returns the results
               var MachineObject = JSON.parse(data);
               console.log(MachineObject);
               $('#MachineDetailsDisplay').append(
                machineDetails);
            });
            
        });

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top