We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

Unable to load dataSource Dynamically through JQuery Ajax Call

Hi Team,

I am using Javascript ejGrid to display data dynamically.
At the initial load it loads data from the server, but it fails to load data after a call through Ajax call, below is my source code

The below code does not throws any error, and data is till empty.

But the server call has data.

Client Side:

<script type="text/javascript">

    $.ajaxPrefilter(function (options, original_Options, jqXHR) {
        options.async = true;
    });

    function RefreshGrid(data) {
        var gridData = ej.parseJSON(data);
        var gridModel = $("#Grid").ejGrid("model");
        //$("#Grid").data("ejGrid") !== undefined && $("#Grid").ejGrid("destroy")// destroy the grid if already rendered
        gridModel.query = new ej.Query();//clear the queries
        gridModel.dataSource = gridData;//binding the data to grid 
       
        $("#Grid").ejGrid(gridModel);
        var gridObj = $("#Grid").data("ejGrid");       
        // Refreshes the grid data source
        gridObj.dataSource(data); // tried no use
        gridObj.dataSource(data, true); // tried no use
        gridObj = $("#Grid").ejGrid("instance"); // tried no use
        gridObj.dataSource(data); // tried no use
        gridObj.dataSource(data, true); // tried no use
        alert("Refreshed...");
       
    }
    var successMessage = function (data) {       
        console.log("Data:" + data);
        RefreshGrid(data);
       console.log("Data Loaded to Grid...");
    }
    var errorMessage = function (error) {
        console.log("Error :" + error);      
    }

    $("#getData").click(function () {

        //JsUpdate('http://localhost:2422/Orders?test=data&t1=44&ship_country=India',
        //    "GET", "", "", successMessage, errorMessage); // Not works.

        FilterGridData(); // This works Perfectly
        //ref: https://www.syncfusion.com/kb/5963/how-to-send-custom-headers-to-server-using-datamanager
    });


    function FilterGridData() {

        var dataManager = ej.DataManager({
            url: "http://localhost:2422/Orders?test=data&t1=44&ship_country=India",
            enableCaching: true,
            cachingPageSize: 10,
            timeTillExpiration: 120000,
            adaptor: new ej.WebApiAdaptor()

        });

        $("#Grid").ejGrid({
            dataSource: dataManager,
            rowSelected: "rowSelected", // "rowSelected" is a function           

            allowPaging: true,
            pageSettings: { pageSize: 10 }, //pageSizeList: [5, 10, 15, 20]
            columns: [
                        { field: "OrderID", isPrimaryKey: true },
                        { field: "CustomerID" },
                        { field: "Freight", editType: "numericedit" },
                        { field: "EmployeeID" },
                        { field: "ShipCountry" }
            ],
            load: function (args) {
                //this.model.dataSource.dataSource.headers = [];//So define them as array
                //this.model.dataSource.dataSource.headers.push({ "fromDate": "12-06-2017" });//pushing Some JSON Object
                //this.model.dataSource.dataSource.headers.push({ "toDate": "18-06-2017" });//pushing Some JSON Object
            }
        });
    }

    function LoadAllGridData() {

        var dataManager = ej.DataManager({
            url: "http://localhost:2422/Orders",
            enableCaching: true,
            cachingPageSize: 10,
            timeTillExpiration: 120000,
            adaptor: new ej.WebApiAdaptor()

        });

        $("#Grid").ejGrid({
            dataSource: dataManager,
            rowSelected: "rowSelected", // "rowSelected" is a function           

            allowPaging: true,
            pageSettings: { pageSize: 10 }, //pageSizeList: [5, 10, 15, 20]
            columns: [
                        { field: "OrderID", isPrimaryKey: true },
                        { field: "CustomerID" },
                        { field: "Freight", editType: "numericedit" },
                        { field: "EmployeeID" },
                        { field: "ShipCountry" }
            ],
            load: function (args) {
                this.model.dataSource.dataSource.headers = [];//So define them as array
                this.model.dataSource.dataSource.headers.push({ "fromDate": "12-06-2017" });//pushing Some JSON Object
                this.model.dataSource.dataSource.headers.push({ "toDate": "18-06-2017" });//pushing Some JSON Object
            }
        });
    }

        function rowSelected(args)
        {
            var selectedrowindex = this.selectedRowsIndexes;  // get selected row indexes            
            console.log("Selected Index: " +selectedrowindex);
            var selectedrecords = this.getSelectedRecords();  // get selected records 
        }

        $("#Grid").dblclick(function () {
            var gridObj = $("#Grid").ejGrid("instance");
            var selectedrecords = gridObj.getSelectedRecords();
           
            if (selectedrecords[0] != undefined) {
                //Edit operation here
                console.log(selectedrecords[0])
                gridObj.refreshContent();
            }           
           
            console.log("Ready to Edit");
        });


        $('#Grid').keyup(function (e) {
            if (e.keyCode == 46) {
                var gridObj = $("#Grid").ejGrid("instance");
                var selectedrecords = gridObj.getSelectedRecords();
               
                if (selectedrecords[0] != undefined) {
                    //Delete operation here
                    console.log("Ready to Delete :" + selectedrecords[0])
                    gridObj.refreshContent();
                }
                console.log('Delete key released');
            }
        });

    $(function () {
        LoadAllGridData(); // Works When page Load.
       
    });
    </script>

Server Side:

[Route("Orders")]
        [HttpGet]       
        public object GetObject()
        {
            var queryString = HttpContext.Current.Request.QueryString;
            int skip = Convert.ToInt32(queryString["$skip"]);
            int take = Convert.ToInt32(queryString["$top"]);
           
           
            if (string.IsNullOrEmpty(queryString["ship_country"]))
            {
                var data = _lst.Skip(skip).Take(take).ToList();
                _lstCurrent = data;               
            }
            else
            {
                string shipCountry = queryString["ship_country"].ToString();
                var filterData = _lst.Where(ord => ord.ShipCountry.Equals(shipCountry)).ToList();
                var data = _lst.Skip(skip).Take(take).ToList();
                _lstCurrent = filterData;
            }
           
            return new
            {
                Items = _lstCurrent,
                Count = _lstCurrent.Count
            };
        }

I have also attached Server side code and client side code for your reference..

Please let me know what went wrong in my code.

Thanks in advance.



Attachment: Sync_7f7466f4.zip

5 Replies

SA Saravanan Arunachalam Syncfusion Team October 9, 2017 07:33 AM UTC

Hi Ganesh, 
Thanks for contacting Syncfusion’s support. 
We have analyzed you reported query and we suspect that the data in sucessMessage call back is formatted like Items and Count which may be the cause of the issue. So, please ensure the data which you have return from the server and hence provide the following details to us. 
1.       Confirm, the “data” in the successMessage callback is formatted like Items and Count. 
2.       Share the “data” in the successMessage callback to us. 
Regards, 
Saravanan A. 



GR Ganesh Ram SR October 9, 2017 10:42 AM UTC

Please refer the data I have shared

Also I have provided JsUdate Ajax code.

function JsUpdate(URL, Method, data, model, succMsg, errMsg) {

    var result;

    $.ajax({

        url: URL,

        type: Method,

        data: JSON.stringify(data),

        async: false,

        cache: false,

        dataType: 'json',

        contentType: "application/json;charset=utf-8",

        success: function (data) {

            result = data;

            succMsg(data);

            //alert(model + ' added Successfully');

        },

        error: function (err) {

            errMsg(err);

            //alert(model + ' not Added');

        }

    });

    return result;}


Sample Data:


{

    "Items": [

        {

            "OrderID": "OR-1",

            "EmployeeID": 1,

            "CustomerID": null,

            "ShipCountry": "India",

            "Freight": 1

        },

        {

            "OrderID": "OR-2",

            "EmployeeID": 2,

            "CustomerID": null,

            "ShipCountry": "India",

            "Freight": 2

        },

        {

            "OrderID": "OR-3",

            "EmployeeID": 3,

            "CustomerID": null,

            "ShipCountry": "India",

            "Freight": 3

        },

        {

            "OrderID": "OR-4",

            "EmployeeID": 4,

            "CustomerID": null,

            "ShipCountry": "India",

            "Freight": 4

        },

        {

            "OrderID": "OR-5",

            "EmployeeID": 5,

            "CustomerID": null,

            "ShipCountry": "India",

            "Freight": 5

        },

        {

            "OrderID": "OR-6",

            "EmployeeID": 6,

            "CustomerID": null,

            "ShipCountry": "India",

            "Freight": 6

        },

        {

            "OrderID": "OR-7",

            "EmployeeID": 7,

            "CustomerID": null,

            "ShipCountry": "India",

            "Freight": 7

        },

        {

            "OrderID": "OR-8",

            "EmployeeID": 8,

            "CustomerID": null,

            "ShipCountry": "India",

            "Freight": 8

        },

        {

            "OrderID": "OR-9",

            "EmployeeID": 9,

            "CustomerID": null,

            "ShipCountry": "India",

            "Freight": 9

        },

        {

            "OrderID": "OR-10",

            "EmployeeID": 10,

            "CustomerID": null,

            "ShipCountry": "India",

            "Freight": 10

        }

    ],

    "Count": 15

}





SA Saravanan Arunachalam Syncfusion Team October 10, 2017 04:35 AM UTC

Hi Ganesh, 
We have analyzed your provided code example, the cause of the issue is that you have tried to bind the data (which is return from the server like Items and Count) to the Grid control. So, we suggest you to bind the Items from the returned data to the Grid control and please refer to the below code example. 
$.ajax({ 
         . . . 
        success: function (data) { 
            result = data; 
            succMsg(data.Items); 
        }, 
    }); 
 
Note: If we rendered the Grid with WebApi adaptor, we should return the data from the server like Items and Count which is render the Grid based on the Items and set the total records based on the Count and please refer to the below UG document link. 
Regards, 
Saravanan A.  



GR Ganesh Ram SR replied to Saravanan Arunachalam October 10, 2017 08:31 AM UTC

Hi Ganesh, 
We have analyzed your provided code example, the cause of the issue is that you have tried to bind the data (which is return from the server like Items and Count) to the Grid control. So, we suggest you to bind the Items from the returned data to the Grid control and please refer to the below code example. 
$.ajax({ 
         . . . 
        success: function (data) { 
            result = data; 
            succMsg(data.Items); 
        }, 
    }); 
 
Note: If we rendered the Grid with WebApi adaptor, we should return the data from the server like Items and Count which is render the Grid based on the Items and set the total records based on the Count and please refer to the below UG document link. 
Regards, 
Saravanan A.  


Wow It works. Many Thanks.



SA Saravanan Arunachalam Syncfusion Team October 11, 2017 06:14 AM UTC

Hi Ganesh,  
Thanks for your update.            
We are happy that the provided information helped you. 
Regards, 
Saravanan A. 


Loader.
Live Chat Icon For mobile
Up arrow icon