Brendan Gooden
Brendan Gooden

Reputation: 1551

AJAX response being used in variable

I have an function with AJAX call as follows:

$(function AddItemsToCart() {
    $('#AddToCartBtn').click(function () {
        var cartData = new Array();

        if ($("#PartsTable> tr").length > 0) {
            var popupMsgTxt = '';
            var counter = 0;
            $('#PartsTable').find('tr').each(function () {
                var row = $(this);


                if (row.find('input[type="checkbox"]').is(':checked')) {



                    var cartDataInfo = new Object();
                    var $tds = $(this).find('td');

                    cartDataInfo["CustomerReference"] = $tds.eq(0).find('div').text();
                    cartDataInfo["Quantity"] = $tds.eq(2).find('div').text();

                    var $hidden_fields = $(this).find('input:hidden');
                    cartDataInfo["ItemID"] = $hidden_fields.eq(1).val();
                    cartDataInfo["ItemCode"] = $hidden_fields.eq(0).val();
                    popupMsgTxt = $tds.eq(0).find('div').text();

                    cartData[counter] = cartDataInfo;
                    counter = counter + 1;
                }
            });

            var cartDataArray = { 'cartData': cartData };
            var fleetGuid;

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "OrderFormServices.asmx/AddItemsToCart",
                data: JSON.stringify(cartDataArray),
                dataType: "json",
                success: function (result) {
                    fleetGuid = result.d;
                    console.log(fleetGuid);
                }
            });

            var items = [], options = [];

            //Iterate all td's in first column
            $('#PartsTable tr td:nth-child(1)').each(function () {
                items.push($(this).text());
            });

            //restrict array to unique fleet numbers
            items = $.unique(items);

            //iterate unique array and build array of select options
            $.each(items, function(i, item) {

            //// THIS IS WHERE I AM GETTING THE 'UNDEFINED' ERROR ////

                options.push('<tr><td align="left" valign="top">' + item + '</td><input type="hidden" name="GUID" value="'+ fleetGuid +'"><td class="delete" align="center" style="background-color: transparent;"><i class="fa fa-times text-red cur-pon"></i></td></tr>');
            });

            //finally empty the select and append the items from the array
            $('#OrderSummaryTbody').append(options.join());

            $("#PopupInnerTextModel").text(popupMsgTxt);
            $("#popup").fadeIn(750).delay(1750).fadeOut(500);


        }
    });
});

The response successfully logs in my console log, as per below

enter image description here

However, when I try and use the variable 'fleetGuid' in a function (you will see the comment in my code above), it returns undefined. Could this be beacuse there is a delay in getting the response from the server?

Can anyone shed any light?

Upvotes: 0

Views: 37

Answers (2)

madalinivascu
madalinivascu

Reputation: 32354

Do your logic in the success function of your ajax call

$(function AddItemsToCart() {
    $('#AddToCartBtn').click(function () {
        var cartData = new Array();

        if ($("#PartsTable> tr").length > 0) {
            var popupMsgTxt = '';
            var counter = 0;
            $('#PartsTable').find('tr').each(function () {
                var row = $(this);


                if (row.find('input[type="checkbox"]').is(':checked')) {



                    var cartDataInfo = new Object();
                    var $tds = $(this).find('td');

                    cartDataInfo["CustomerReference"] = $tds.eq(0).find('div').text();
                    cartDataInfo["Quantity"] = $tds.eq(2).find('div').text();

                    var $hidden_fields = $(this).find('input:hidden');
                    cartDataInfo["ItemID"] = $hidden_fields.eq(1).val();
                    cartDataInfo["ItemCode"] = $hidden_fields.eq(0).val();
                    popupMsgTxt = $tds.eq(0).find('div').text();

                    cartData[counter] = cartDataInfo;
                    counter = counter + 1;
                }
            });

            var cartDataArray = { 'cartData': cartData };
            var fleetGuid;

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "OrderFormServices.asmx/AddItemsToCart",
                data: JSON.stringify(cartDataArray),
                dataType: "json",
                success: function (result) {
                    fleetGuid = result.d;
                                var items = [], options = [];

            //Iterate all td's in first column
            $('#PartsTable tr td:nth-child(1)').each(function () {
                items.push($(this).text());
            });

            //restrict array to unique fleet numbers
            items = $.unique(items);

            //iterate unique array and build array of select options
            $.each(items, function(i, item) {

            //// THIS IS WHERE I AM GETTING THE 'UNDEFINED' ERROR ////

                options.push('<tr><td align="left" valign="top">' + item + '</td><input type="hidden" name="GUID" value="'+ fleetGuid +'"><td class="delete" align="center" style="background-color: transparent;"><i class="fa fa-times text-red cur-pon"></i></td></tr>');
            });

            //finally empty the select and append the items from the array
            $('#OrderSummaryTbody').append(options.join());

            $("#PopupInnerTextModel").text(popupMsgTxt);
            $("#popup").fadeIn(750).delay(1750).fadeOut(500);
                }
            });




        }
    });
});

Upvotes: 1

Kalpesh Rajai
Kalpesh Rajai

Reputation: 2056

Yes it is correct because the success function of ajax is called letter, it called when it got the response from the server, and you used that var before the you got the reply,

$(function AddItemsToCart() {
    $('#AddToCartBtn').click(function () {
        var cartData = new Array();

        if ($("#PartsTable> tr").length > 0) {
            var popupMsgTxt = '';
            var counter = 0;
            $('#PartsTable').find('tr').each(function () {
                var row = $(this);


                if (row.find('input[type="checkbox"]').is(':checked')) {



                    var cartDataInfo = new Object();
                    var $tds = $(this).find('td');

                    cartDataInfo["CustomerReference"] = $tds.eq(0).find('div').text();
                    cartDataInfo["Quantity"] = $tds.eq(2).find('div').text();

                    var $hidden_fields = $(this).find('input:hidden');
                    cartDataInfo["ItemID"] = $hidden_fields.eq(1).val();
                    cartDataInfo["ItemCode"] = $hidden_fields.eq(0).val();
                    popupMsgTxt = $tds.eq(0).find('div').text();

                    cartData[counter] = cartDataInfo;
                    counter = counter + 1;
                }
            });

            var cartDataArray = { 'cartData': cartData };
            var fleetGuid;

            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: "OrderFormServices.asmx/AddItemsToCart",
                data: JSON.stringify(cartDataArray),
                dataType: "json",
                success: function (result) {
                    fleetGuid = result.d;
                    doWork();
                    console.log(fleetGuid);
                }
            });

            function doWork(){



            var items = [], options = [];

            //Iterate all td's in first column
            $('#PartsTable tr td:nth-child(1)').each(function () {
                items.push($(this).text());
            });

            //restrict array to unique fleet numbers
            items = $.unique(items);

            //iterate unique array and build array of select options
            $.each(items, function(i, item) {

            //// THIS IS WHERE I AM GETTING THE 'UNDEFINED' ERROR ////

                options.push('<tr><td align="left" valign="top">' + item + '</td><input type="hidden" name="GUID" value="'+ fleetGuid +'"><td class="delete" align="center" style="background-color: transparent;"><i class="fa fa-times text-red cur-pon"></i></td></tr>');
            });

            //finally empty the select and append the items from the array
            $('#OrderSummaryTbody').append(options.join());

            $("#PopupInnerTextModel").text(popupMsgTxt);
            $("#popup").fadeIn(750).delay(1750).fadeOut(500);
            }


        }
    });
});

So do the following to do work correctly...

Happy Coding!!!

Upvotes: 1

Related Questions