[Solved] Nested Ajax Call not firing using jQuery in ASP.Net

ishi12.shah
 
on Jan 26, 2021 05:05 AM
Sample_158150.zip
2858 Views

Nested Ajax Call but Second is not firing while direct click on button

When I click on Add button and I debug javascript then Nested ajax is working properly but when I click on add button without debugging then First ajax is executed fine but second ajax is not fired.

    $("[id*=btnAdd]").bind("click", function () {
        debugger
        var returnValue = true;
        var return_response = false;
        var msg = "";
        if ($("[id*=txtsuppliername]").val() == "") {
            msg += "Supplier Code not Correct..\n";
            returnValue = false;
        }
        if ($("[id*=txtchallanno]").val() == "0") {
            msg += "Challan Number is not zero..\n";
            returnValue = false;
        }
        if ($("[id*=txtchallandate]").val() == "") {
            msg += "Please Select Challandate..\n";
            returnValue = false;
        }
        if (!returnValue) {
            alert(msg);
            return returnValue;
        }
        else {
           
            var grn = {};
            ShowProgress();

            grn.GRNMaterialType = $.trim($("[id*=ddlGrnMaterialType]").find("option:selected").val());
            grn.GRNCode = $.trim($("[id*=txtgrncode]").val());
            grn.GRNDate = $.trim($("[id*=txtgrnDate]").val());
            grn.GRNType = $.trim($("[id*=ddlgrntype]").find("option:selected").val());

            grn.SupplierCode = parseInt($("[id*=txtsuppliercode]").val());
            grn.SupplierName = $.trim($("[id*=txtsuppliername]").val());
            grn.GSTNo = $.trim($("[id*=txtsuppliergst]").val());

            grn.ChallanNo = $.trim($("[id*=txtchallanno]").val());
            grn.ChallanDate = $.trim($("[id*=txtchallandate]").val());
            grn.Remarks = $.trim($("[id*=txtRemark]").val());

            grn.GstAmount = parseFloat($("[id*=txtgst_amount]").val());
            grn.NetAmount = parseFloat($("[id*=txtnet_amount]").val());
            grn.GrossPayAmount = parseFloat($("[id*=txtgrosspayamount]").val());
            grn.NetPayAmount = parseFloat($("[id*=txtnetpayamount]").val());
            grn.Amount_D = parseFloat($("[id*=txt_Amount]").val());
            grn.DisAmount = parseFloat($("[id*=txtdiscountAmount]").val());

            grn.Validitydays = ($("[id*=txtvaliditydays]").val() == "" ? "0" : parseInt($("[id*=txtvaliditydays]").val()));
            grn.CurrencyCode = parseInt($("[id*=ddlcurrency]").find("option:selected").val());
            grn.IsApproved = "N";
            grn.Authorizedid = "";
            grn.PONo = $.trim($("[id*=txtSupplierPONo]").val()) == "" ? "0" : $.trim($("[id*=txtSupplierPONo]").val());


            // alert(JSON.stringify(grn));
            
            $.ajax({
                type: "POST",
                url: currLoc + '/SaveGRN',
                data: '{grn: ' + JSON.stringify(grn) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                async: true,
                success: function (response) {
                    alert(response.d);
                    return_response = response.d;
                    if (return_response) {
                        debugger

                        var GrnDetail = [];

                        var SelectedGRNMaterialType = $.trim($("[id*=ddlGrnMaterialType]").find("option:selected").val());
                        var SelectedGRNType = $.trim($("[id*=ddlgrntype]").find("option:selected").val());
                        var GRNCode = $.trim($("[id*=txtgrncode]").val());

                        $("[id*=grdDetail] tr:not(:first)").each(function () {
                            var obj = {};

                            obj.GRNCode = GRNCode;
                            obj.GRNMaterialType = SelectedGRNMaterialType;
                            obj.GRNType = SelectedGRNType;

                            obj.ItemTypeCode = ($(this).find("[id*=lblitemtypecode]").text() == "" ? "0" : $(this).find("[id*=lblitemtypecode]").text());
                            obj.ItemCode = $(this).find("[id*=lblitemcode]").text();
                            obj.UoM = $(this).find("[id*=lblitem_uom]").text();
                            obj.PurcahseCode = $(this).find("[id*=lblpocode]").text();
                            obj.POQty = parseFloat($(this).find("[id*=lblHpoitemqty]").text());
                            obj.ItemPieces = parseFloat($(this).find("[id*=lblHpoitempieces]").text());
                            obj.PORate = parseFloat($(this).find("[id*=txtHpoitemrate]").val());
                            //obj.Size = parseFloat(($(this).find("[id*=txtISize]").val() == "" ? "0" : $(this).find("[id*=txtISize]").val())).toFixed(2);
                            obj.Size = $(this).find("[id*=txtISize]").val();
                            obj.BaleNo = $(this).find("[id*=txtIBaleNo]").val();

                            obj.RollNo = $(this).find("[id*=txtIRollNo]").val();
                            obj.DesignNo = $(this).find("[id*=txtIDesignNo]").val();
                            obj.Color = $(this).find("[id*=txtIColor]").val();
                            obj.ActualGRNQty = parseFloat($(this).find("[id*=txtHqtyreceived]").val());

                            obj.POAmount = parseFloat($(this).find("[id*=lblamount]").text());
                            obj.PODiscount = parseFloat($(this).find("[id*=txtHdiscount]").val());
                            obj.NetAmount = parseFloat($(this).find("[id*=lblnetamount]").text());
                            obj.GSTRate = parseFloat($(this).find("[id*=txtHgstrate]").val());

                            obj.GSTAmount = parseFloat($(this).find("[id*=lblgstamount]").text());
                            obj.GrossAmount = parseFloat($(this).find("[id*=lblgrossamount]").text());
                            obj.ChallanQty = parseFloat($(this).find("[id*=txtHChaqtyreceived]").val());
                            obj.SupplierCode = parseInt($(this).find("[id*=hfSupplierId]").val() == "" ? "0" : $(this).find("[id*=hfSupplierId]").val());

                            obj.ShrinkWidth = parseFloat($(this).find("[id*=txtShrinkWidth]").val() == "" ? "0" : $(this).find("[id*=txtShrinkWidth]").val());
                            obj.ShrinkLength = parseFloat($(this).find("[id*=txtShrinkLength]").val() == "" ? "0" : $(this).find("[id*=txtShrinkLength]").val());
                            obj.DiscountType = $.trim($(this).find("[id*=ddlHDiscountType]").find("option:selected").text());
                            obj.DiscountPer = parseFloat($(this).find("[id*=txtHdiscountAmt]").val() == "" ? "0" : $(this).find("[id*=txtHdiscountAmt]").val());
                            GrnDetail.push(obj);
                        });
                        GrnDetail.pop();
                        GrnDetail = JSON.stringify({ 'GrnDetail': GrnDetail });
                        alert(GrnDetail);
                        $.ajax({
                            type: "POST",
                            url: currLoc + '/SaveGRNItemDetail',
                            data: GrnDetail,
                            contentType: "application/json; charset=utf-8",
                            dataType: "json",
                            async: true,
                            success: function (response) {
                                alert("hi done!");
                                window.location = 'MaterialGRNList.aspx';
                            },
                            failure: function (response) { alert(response.d); },
                            error: function (response) { alert(response.d); }
                        });
                    }
                    else {
                        return false;
                    }
                },
                error: function (response) {
                    alert(response.d);
                },
                failure: function (response) {
                    alert(response.d);
                }
            });

           


        }
    });

    function ShowProgress() {
        alert("hello");
        setTimeout(function () {
            var modal = $('<div />');
            modal.addClass("modal");
            $('body').append(modal);
            var loading = $(".loading");
            loading.show();
            var top = Math.max($(window).height() / 2 - loading[0].offsetHeight / 2, 0);
            var left = Math.max($(window).width() / 2 - loading[0].offsetWidth / 2, 0);
            loading.css({ top: top, left: left });
        }, 200);
    }

 

    [System.Web.Script.Services.ScriptMethod]
    [System.Web.Services.WebMethod]
    public static bool SaveGRN(GRN grn)
    {

        System.Threading.Thread.Sleep(5000);

        Int32 f_int_ErrCode = 0;
        string f_str_ErrMsg = "";

        BAL bl = new BAL();
        DAL dl = new DAL();
        try
        {
            bl.GRNType = grn.GRNType;
            bl.GRNCode = grn.GRNCode;
            bl.GRNDate = grn.GRNDate;
            bl.SupplierCode = grn.SupplierCode;
            bl.SupplierName = grn.SupplierName;
            bl.GSTNo = grn.GSTNo;
            bl.ChallanNo = grn.ChallanNo;
            bl.ChallanDate = grn.ChallanDate;
            bl.Remarks = grn.Remarks;
            bl.GstAmount = grn.GstAmount;
            bl.NetAmount = grn.NetAmount;
            bl.GrossPayAmount = grn.GrossPayAmount;
            bl.NetPayAmount = grn.NetPayAmount;
            bl.Amount_D = grn.Amount_D;
            bl.DisAmount = grn.DisAmount;
            bl.Validitydays = grn.Validitydays;
            bl.CurrencyCode = grn.CurrencyCode;
            bl.IsApproved = grn.IsApproved;
            bl.Authorizedid = grn.Authorizedid;
            bl.GRNMaterialType = grn.GRNMaterialType;
            bl.LoginName = HttpContext.Current.Session["UserID"].ToString();
            bl.CompanyCode = HttpContext.Current.Session["HospitalID"].ToString().Trim();
            bl.PONo = grn.PONo;

            dl.ENGG_GRN_Save(bl, ref f_int_ErrCode, ref f_str_ErrMsg);
            LogDetailSave("A", grn.GRNCode);
            return true;
        }
        catch (Exception ex)
        {
            return false;
            //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Alert", "alert('" + Server.HtmlEncode(ex.Message) + "');", true);
        }
    }

    static void LogDetailSave(string TranType, string GRNCode)
    {
        try
        {

            BAL bl = new BAL();
            DAL dl = new DAL();

            bl.FormID = "/Modules/Store/Trans/MaterialGRNList.aspx"; //Convert.ToString(HttpContext.Current.Request.Url.AbsolutePath);
            bl.LoginName = HttpContext.Current.Session["UserID"].ToString();
            bl.MachineIP = System.Net.Dns.GetHostAddresses(System.Net.Dns.GetHostName()).GetValue(1).ToString();
            bl.TranType = TranType;
            bl.pri_key = GRNCode;
            dl.LogDetail_Save(bl);
        }
        catch (Exception ex)
        {
            throw ex;
            //ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "Alert", "alert('" + Server.HtmlEncode(ex.Message) + "');", true);
        }
    }

    [WebMethod]
    public static bool SaveGRNItemDetail(GRNDetail[] GrnDetail)
    {
        
        try
        {
            DataSet f_dset_Temp = new DataSet();
            Int32 f_int_ErrCode = 0;
            string f_str_ErrMsg = "";

            //GRNDetail[] grndetail = GrdDetail;

            BAL bl = new BAL();
            DAL dl = new DAL();

            //for (int i = 0; i < grndetail.Count; i++)
            foreach (var grndetail in GrnDetail)
            {
                bl.GRNCode = grndetail.GRNCode;
                bl.GRNType = grndetail.GRNType;
                bl.GRNMaterialType = grndetail.GRNMaterialType;
                bl.ItemTypeCode = grndetail.ItemTypeCode;
                bl.ItemCode = grndetail.ItemCode;
                bl.UoM = grndetail.UoM;
                bl.PurcahseCode = grndetail.PurcahseCode;
                bl.POQty = grndetail.POQty;
                bl.ItemPieces = grndetail.ItemPieces;
                bl.PORate = grndetail.PORate;
                bl.Size = grndetail.Size;
                bl.BaleNo = grndetail.BaleNo;
                bl.RollNo = grndetail.RollNo;
                bl.DesignNo = grndetail.DesignNo;
                bl.Color = (grndetail.Color == "" ? grndetail.Color : grndetail.Color.ToUpper());
                bl.ActualGRNQty = grndetail.ActualGRNQty;
                bl.POAmount = grndetail.POAmount;
                bl.PODiscount = grndetail.PODiscount;
                bl.NetAmount = grndetail.NetAmount;
                bl.GSTRate = grndetail.GSTRate;
                bl.GSTAmount = grndetail.GSTAmount;
                bl.GrossAmount = grndetail.GrossAmount;
                bl.ChallanQty = grndetail.ChallanQty;
                bl.CompanyCode = HttpContext.Current.Session["HospitalID"].ToString().Trim();
                bl.SupplierCode = grndetail.SupplierCode;
                bl.ShrinkWidth = grndetail.ShrinkWidth;
                bl.ShrinkLength = grndetail.ShrinkLength;
                bl.DiscountType = grndetail.DiscountType;
                bl.DiscountPer = grndetail.DiscountPer;

                dl.ENGG_GRNOrderDetail_Save(bl, ref f_int_ErrCode, ref f_str_ErrMsg);
            }
            return true;

        }
        catch (Exception ex)
        {
            return false;
        }
    }

Please give me idea

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Jan 27, 2021 03:53 AM

Hi ishi12.shah,

There is no need to make nested Ajax call. Create a class to return all the data and make a ajax call to save the records.

Refer below example.

HTML

<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
<asp:TextBox ID="txtCode" runat="server"></asp:TextBox>
<hr />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Id" />
        <asp:BoundField DataField="Name" HeaderText="Name" />
    </Columns>
</asp:GridView>
<asp:Button ID="btnAdd" Text="Add" runat="server" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("[id*=btnAdd]").bind("click", function () {
            var grn = {};
            grn.GRNName = $.trim($("[id*=txtName]").val());
            grn.GRNCode = $.trim($("[id*=txtCode]").val());

            var GrnDetail = [];
            $("[id*=GridView1] tr:not(:first)").each(function () {
                var obj = {};
                obj.Id = $(this).find('td').eq(0).html();
                obj.Name = $(this).find('td').eq(1).html();
                GrnDetail.push(obj);
            });
            grn.GRNDetails = GrnDetail;

            $.ajax({
                type: "POST",
                url: "Default.aspx/SaveGRN",
                data: '{grn: ' + JSON.stringify(grn) + '}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function OnSuccess(response) {
                    alert(response.d);
                },
                error: function (response) {
                    alert(response.d);
                }
            });
        });
    });
</script>

Code

protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        System.Data.DataTable dt = new System.Data.DataTable();
        dt.Columns.AddRange(new System.Data.DataColumn[]
        {
            new System.Data.DataColumn("Id"),
            new System.Data.DataColumn("Name")
        });
        dt.Rows.Add(1, "TShirt");
        dt.Rows.Add(2, "Cap");
        dt.Rows.Add(3, "Jeans");
        dt.Rows.Add(4, "Shoe");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}

[System.Web.Script.Services.ScriptMethod]
[System.Web.Services.WebMethod]
public static bool SaveGRN(GRN grn)
{
    Int32 f_int_ErrCode = 0;
    string f_str_ErrMsg = "";

    DAL dl = new DAL();
    BAL bl = new BAL();
    bl.GRNName = grn.GRNName;
    bl.GRNCode = grn.GRNCode;
    dl.LogDetail_Save(bl);

    dl = new DAL();
    foreach (GRNDetail detail in grn.GRNDetails)
    {
        bl = new BAL();
        bl.Id = detail.Id;
        bl.Name = detail.Name;
        dl.ENGG_GRNOrderDetail_Save(bl, ref f_int_ErrCode, ref f_str_ErrMsg);
    }

    return true;
}

public class GRN
{
    public string GRNName { get; set; }
    public string GRNCode { get; set; }
    public GRNDetail[] GRNDetails { get; set; }
}

public class GRNDetail
{
    public int Id { get; set; }
    public string Name { get; set; }
}