0

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?

Brendan Gooden
  • 1,460
  • 2
  • 21
  • 40
  • above this line: `$(function AddItemsToCart() {` define your variable like this: `var fleetGuid;` – HarisH Sharma Jul 04 '16 at 04:58
  • I see there is an unwanted double quote after value= just before fleetGuid – Allen King Jul 04 '16 at 05:02
  • Possible duplicate of [How do I return the response from an asynchronous call?](http://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call) – madalinivascu Jul 04 '16 at 05:16

2 Answers2

1

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!!!

Kalpesh Rajai
  • 2,040
  • 27
  • 39
1

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




        }
    });
});
madalinivascu
  • 32,064
  • 4
  • 39
  • 55