Skip to content
Advertisement

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

I’m using JQUERY and AJAX, and it currently seems like the function sort of works but after the next line of code has run. This means that when the script aims to add the object to the html it adds a null value.

My intention with this function is that on the change of drop down it grabs an object from my backend(asp.net) and adds to my HTML.

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

                    return machineDetails = response.responseJSON;

                },
                failure: function (xhr, ajaxOptions, thrownError) {
                    alert("Error: " + thrownError);
                }
            });

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

            removeAllChildren('MachineDetailsDisplay');
            var SelectedMachine = $('#SelectMachines option:selected');
            getMachineDetails(SelectedMachine[0].value);
            var MachineObject = machineDetails;
            console.log(MachineObject);
            $('#MachineDetailsDisplay').append(
                machineDetails);
        });

Advertisement

Answer

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);
            });
            
        });
Advertisement