0

When form load at that time I am calling .asmx.cs page via Ajax at that time getting error

SyntaxError: Unexpected non-whitespace character after JSON at position 221 (line 1 column 222)

Here is my Ajax code:

window.addEventListener('load', function () {                 
    var date1 = document.getElementById('<%= dtp_from.ClientID %>').value || new Date().toISOString().split('T')[0]; // Default to today if empty
    var date2 = document.getElementById('<%= dtp_to.ClientID %>').value || new Date().toISOString().split('T')[0];
    var dataToSend = JSON.stringify({ fromDate: date1, toDate: date2 });            
    $.ajax({
        type: "POST",
        url: "FillGridMethod.asmx/CashBookList",                    
        async: true,
        data: dataToSend,
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            alert();
            var datatableVariable = $('#gv_Datatable').DataTable({
                dom: 'Bfrtip',
                buttons: [
                    'pdf', 'print', 'excel'
                ],
                "bDestroy": true,
                "paging": true,
                "searching": true,
                "ordering": true,
                "info": true,
                "autoWidth": false,
                "responsive": true,
                data: data,
                columns: [
                    {
                        className: 'dt-control',
                        orderable: false,
                        data: null,
                        defaultContent: ''
                    },
                    { 'data': 'Id', visible: false },
                    {
                        'data': 'cashbookdate', 'render': function (date) {
                            var date = new Date(parseInt(date.substr(6)));
                            var month = date.getMonth() + 1;
                            return date.getDate() + "/" + month + "/" + date.getFullYear();
                        }
                    },
                    { 'data': 'cashbookaccname' },
                    { 'data': 'cashbookreceipt' },
                    { 'data': 'cashbookpayment' },
                    { 'data': 'Balance' },
                    {
                        "render": function (data, type, row) { return "<a href='#' class='btn btn-success' onclick=DeleteCustomer('" + row.Id + "');>View</>"; }
                    },
                    {
                        "render": function (data, row) { return "<a href='#' class='btn btn-danger'>Delete</a>"; }
                    }],
                footerCallback: function (row, data, start, end, display) {
                    var api = this.api();
                    // Calculate the total for the filtered data
                    var total = api.column(4, { page: 'current' }).data().reduce(function (a, b) {
                        return parseFloat(a) + parseFloat(b);
                    }, 0);
                    // Update the footer with the total
                    $(api.column(4).footer()).html(total.toFixed(2));

                    // Calculate the total for the filtered data
                    var total = api.column(5, { page: 'current' }).data().reduce(function (a, b) {
                        return parseFloat(a) + parseFloat(b);
                    }, 0);
                    // Update the footer with the total
                    $(api.column(5).footer()).html(total.toFixed(2));
                }
            });                                                
            $('.showHideDatatable').on('click', function () {
                var tableColumn = datatableVariable.column($(this).attr('data-columnindex'));
                tableColumn.visible(!tableColumn.visible());
            });
            // Add event listener for opening and closing details
            datatableVariable.on('click', 'td.dt-control', function (e) {
                let tr = e.target.closest('tr');
                let row = datatableVariable.row(tr);

                if (row.child.isShown()) {
                    // This row is already open - close it
                    row.child.hide();
                }
                else {
                    // Open this row
                    if (row.data()) {
                        // Open this row
                        row.child(format(row.data())).show();
                    } else {
                        console.error('Row data is undefined');
                    }
                }
            });
        },
        error: function (xhr, status, error) {              
            alert("AJAX Error!\nStatus: " + status + "\nMessage: " + error + "\nResponse: " + xhr.responseText);
        },
        complete: function () {
            // Hide the loading indicator
            $('#loadingOverlay').hide();
        }
    });
});

This is my .asmx.cs code:

[WebMethod(enableSession: true)]
public void CashBookList(string fromDate, string toDate)
{
    if(HttpContext.Current.Session["BranchId"].ToString() == null) {
        Server.Transfer("Index.aspx");
        return;
    }            

    var cashBook = new List<CashBookModel>();
    string constr = cn.ConnectionString;

    using (SqlConnection con = new SqlConnection(constr))
    {
        qryFillGrid = " select cashbookid, cashbookdate, cashbookaccname, Ledger.Name as OthAcc, cashbookdescription, cashbookreceipt, cashbookpayment, Balance " + System.Environment.NewLine;
        qryFillGrid += " from tbl_cashbook cash Left Outer Join tbl_Ledger ledger on ledger.Ledger_ID = cash.OtherAccountId " + System.Environment.NewLine;
        qryFillGrid += " where cash.BranchID = " + HttpContext.Current.Session["BranchID"] + " " + System.Environment.NewLine;

        if (HttpContext.Current.Session["AccountMode"].ToString() != "ALL")
        {
            qryFillGrid += " and AccountMode = '" + HttpContext.Current.Session["AccountMode"].ToString() + "' " + System.Environment.NewLine;
        }

        qryFillGrid += " and convert(varchar(10), convert(datetime, cashbookdate,105),112) >= '" + Convert.ToDateTime(fromDate).Date.ToString("yyyyMMdd") + "' " + System.Environment.NewLine;
        qryFillGrid += " and convert(varchar(10), convert(datetime, cashbookdate,105),112) <= '" + Convert.ToDateTime(toDate).Date.ToString("yyyyMMdd") + "' " + System.Environment.NewLine;
        qryFillGrid += " order by cashbookdate, cashbookid desc " + System.Environment.NewLine;

        var cmd = new SqlCommand(qryFillGrid, con);
        cmd.CommandTimeout = 120; // Timeout in seconds

        con.Open();
        var dr = cmd.ExecuteReader();                

        while (dr.Read())
        {
            var cashBookModel = new CashBookModel
            {
                Id = Convert.ToInt32(dr[0]),
                cashbookdate = Convert.ToDateTime(dr[1]),
                cashbookaccname = dr[2].ToString(),
                OtherAccount = dr[3].ToString(),
                cashbookdescription = dr[4].ToString(),
                cashbookreceipt = Convert.ToDecimal(service.IfNullThen(dr[5], 0)),
                cashbookpayment = Convert.ToDecimal(service.IfNullThen(dr[6], 0)),
                Balance = Convert.ToDecimal(service.IfNullThen(dr[7], 0))
            };
            cashBook.Add(cashBookModel);
        }                
    }

    var js = new JavaScriptSerializer();
    Context.Response.Write(js.Serialize(cashBook));
}

Note: this error is occurring while I am calling parameter, if I remove the parameter, then it's working perfectly.

Here is the output I am getting:

State: parsererror
Error: Unexpected non-whitespace character after JSON at position 221 (line 1 column 222)
Response:
"Id": 1044,
"cashbookdate": "/Date(1741113000000)/",
"cashbookaccname": "RAJU BHAI",
"cashbookreceipt": 500.00,
"cashbookpayment": 0.00,
"cashbookdescription": "",
"Balance": 0,
"totalReceipt": 0,
"totalPayment": 0,
"OtherAccount": ""

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.