Making an j query ajax call work both on page load and with a button click

I have a datatable which gets it's data from an ajax call. Normally ajax runs when the page is loaded and gets the datatable filled with data.

But I want to add some search options to my datatable too. I can send the parameter to server side and get a dataset back with fiters.

What I want to do is, I want the datatable loaded with null parameters at page load, and with a button click send the ajax with parameters and get back filtered data.

What I tried is this

<script>
    //var searchInput ;//search için aramadaki değeri almaya çalışma

    $(document).ready(function TableData(searchInput) {
        var getUrlParameter = function getUrlParameter(sParam) {
            var sPageURL = decodeURIComponent(window.location.search.substring(1)),
                sURLVariables = sPageURL.split('&'),
                sParameterName,
                i;

            for (i = 0; i < sURLVariables.length; i++) {
                sParameterName = sURLVariables[i].split('=');

                if (sParameterName[0] === sParam) {
                    return sParameterName[1] === undefined ? true : sParameterName[1];
                }
            }
        };

        //var searchInput = $("#inpSearch").val();//search için aramadaki değeri almaya çalışma
        var DocumentTypeId = getUrlParameter('DocumentTypeId');
        var Type = getUrlParameter('Type');
        //console.log("dokumantip: " + DocumentTypeId);
        //console.log("tip: " + Type);

        var datatable = null;
        $(document).ready(function () {
            $.extend(true, $.fn.dataTable.defaults, {
                "searching": false,
                "ordering": false
            });


            @*var dataSourceUrl = "@Url.Action(  Inbox ? "InboxList" : "OutboxList" ,"Folder")";*@
            @*var dataSourceUrl = "@Url.Action( Inbox ? "InboxListByType" : "OutboxList" ,"Folder")";*@

            if (Type == 1) {
                var dataSourceUrl = "@Url.Action( Inbox ? "ERPListByType" : "OutboxList" ,"Folder")";
            } else if (Type == 2) {
                var dataSourceUrl = "@Url.Action( Inbox ? "InboxListByType" : "OutboxList" ,"Folder")";
            } else if (Type == 3) {
                var dataSourceUrl = "@Url.Action( Inbox ? "OutboxListByType" : "OutboxList" ,"Folder")";
            } else if (Type == 4) {
                var dataSourceUrl = "@Url.Action( Inbox ? "DeletedDocumentsList" : "OutboxList" ,"Folder")";
            } else {
                //açılış ekranında default gelen kutusu e-TCGB gelsin
                var dataSourceUrl = "@Url.Action( Inbox ? "InboxListByType" : "OutboxList" ,"Folder", new { DocumentTypeID = 3 })";
            }

            if ($.fn.dataTable.isDataTable('#expandabledatatable')) {
                $('#expandabledatatable').dataTable().fnDestroy();
            }

            datatable = $('#expandabledatatable').dataTable({
                //"sDom": "Tflt<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
                //"processing": true,
                //info: false,

                serverSide: true,
                ajax: {
                    "url": dataSourceUrl,
                    "data": { DocumentTypeId: DocumentTypeId, searchInput: searchInput },
                    "type": "POST"
                },
                columns: [
                    {
                        "data": "Id",
                        "render": function (data, type, row) {
                            return "<label><input type='checkbox' value='" + data + "' name='chkGrid'><span class='text'></span></label>";
                        }
                    },
                    { "data": "@Html.Raw(Inbox ? "SenderCompany" : "ReceiverCompany")" },
                    { "data": "DocumentTypeName" },
                    {
                        "data": "RegistrationDate",
                        "render": function (data, type, row) {
                            return moment(parseInt(data.substr(6))).format('DD.MM.YYYY hh:mm');
                        }
                    },
                    {
                        "data": "RegistrationCode",
                        "render": function (data, type, row) {
                            console.log(row);
                            return "<a href='@Url.Action("View","Folder")/" + row["Id"] + "'>" + data + "</a>";
                        }
                    },
                    { "data": "CustomsTransportType" },
                    { "data": "VehicleIdNo" },
                    { "data": null, "defaultContent": "" },
                    { "data": "ConsignorName" },
                    { "data": "ConsigneeName" },
                    { "data": "TotalNoOfPackages" },
                    { "data": "TotalGrossWeight" }
                ],
                iDisplayLength: 10,
                language: {
                    "info": "Toplam kayıt : \_TOTAL\_<br/> Gösterilen : \_START\_ - \_END\_",
                    "paginate": {
                        "first": "İlk",
                        "last": "Son",
                        "next": "İleri",
                        "previous": "Geri"
                    }
                }
            });



        });
    });


    $(document).ready(function () {
        $('#btnSearch').click(function () {
            alert("test");
            TableData($('#inpSearch').val())
        })
    });



</script>

I tried to get the ajax event inside a jquery function with a single parameter so that I could be able to put inside my search button click. But I can' get it work as I want it to be.

EDIT:

data is returned from ActionResult as

string DatatableJson = Utility.DatatableToJson(ds.Tables[0]);

return Content("{ \"draw\": " + Draw + ", \"recordsTotal\" :" + TotalRows + " , \"recordsFiltered\": " + TotalRows + ", \"data\": " + DatatableJson + " } ");

ds is the datatable returning from Database via a stored procedure.

EDIT 2:

I noticed that

$('#btnSearch').click(function () {
            //alert($('#inpSearch').val());
            var search = $('#inpSearch').val();
            TableData(search);
            $('#expandabledatatable').Datatable().draw();
        })

gives a "ReferenceError: TableData is not defined" error. So I think I have a problem with calling the function.

Answers


Try the following:

$(document).ready(function () {
    var url = Object.fromQueryString(window.location.search);

    $.extend(true, $.fn.dataTable.defaults, {
        searching: false,
        ordering: false
    });

    $('#btnSearch').click(function () {
        doSearch( $('#inpSearch').val(), url.Type, url.DocumentTypeId);
    });

    // click the button (do a search) on page load once
    $('#btnSearch').click();
});

Note that this uses Object.fromQueryString() from sugar.js, a very useful library that offers all kinds of helpful stuff. I included that because your getUrlParameter() function is broken and it's not worth fixing that. URL parsers have been written, use an existing one.

You can probably replace moment.js with the Date functions provided by sugar.js as well, if you do not want to increase the number of dependencies.

I have created a doSearch() function that does not depend on any data except what you pass in the arguments. This way the function can be re-used much easier.

function doSearch(searchInput, documentTypeId, type) {
    var dataSourceUrl;

    switch (type) {
        case 1: dataSourceUrl = "@Url.Action( Inbox ? "ERPListByType" : "OutboxList" ,"Folder")"; break;
        case 2: dataSourceUrl = "@Url.Action( Inbox ? "InboxListByType" : "OutboxList" ,"Folder")"; break;
        case 3: dataSourceUrl = "@Url.Action( Inbox ? "OutboxListByType" : "OutboxList" ,"Folder")"; break;
        case 4: dataSourceUrl = "@Url.Action( Inbox ? "DeletedDocumentsList" : "OutboxList" ,"Folder")"; break;
        default: dataSourceUrl = "@Url.Action( Inbox ? "InboxListByType" : "OutboxList" ,"Folder")"; break;
    }

    if ($.fn.dataTable.isDataTable('#expandabledatatable')) {
        $('#expandabledatatable').dataTable().fnDestroy();
    }
    $('#expandabledatatable').dataTable({
        //sDom: "Tflt<'row DTTTFooter'<'col-sm-6'i><'col-sm-6'p>>",
        //processing: true,
        //info: false,
        serverSide: true,
        ajax: {
            url: dataSourceUrl,
            data: { DocumentTypeId: documentTypeId, searchInput: searchInput },
            type: "POST"
        },
        // etc ...
    });
}

Need Your Help

Why isn't the EditorTemplate showing the data?

html asp.net-mvc asp.net-mvc-3 razor

I rewrote my page to use EditorTemplates. And they are very nice. However, when I postback only the first row posts back data. The other 4 rows come up as null. FormSection has a List of FormRowMod...

Databinding combobox selected item to settings

c# wpf data-binding xaml combobox

I store user specified settings using application settings properties and databinding. It has been working fine, until i want user selected to font for combobox. Databinding between user settings and