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 () {

            var SelectedMachine = $('#SelectMachines option:selected');
            .done(function(data) { // <== execute your code when ajax returns the results
               var MachineObject = JSON.parse(data);

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top