Search code examples
jquerykendo-asp.net-mvckendo-autocomplete

Configure Ajax request made by Kendo to support cross domain ajax request


The basic kendo auto complete example shows a setup where matched search results are fetched through an Ajax request. The ajax loading works fine if the requested resource is on the same domain, but I was wondering if there is support for configuring the underlying ajax requests to support CORS. Is there a way to pass in Ajax options like you normally would do if you were using $.ajax({}) directly.

$("#products").kendoAutoComplete({
                        dataTextField: "ProductName",
                        filter: "contains",
                        minLength: 3,
                        dataSource: {
                            type: "odata",
                            serverFiltering: true,
                            serverPaging: true,
                            pageSize: 20,
                            transport: {
                                read: "http://demos.kendoui.com/service/Northwind.svc/Products"
                            }
                        }
                    });
                });

I basically want the same granular control over the request as in a regular JQuery Ajax request (example bellow):

 jQuery.ajax({
                url: 'some url',
                data: {id:id},
                contentType: 'application/json',
                type: "Get",
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true

            })

Solution

  • The solution is to assign the read property to a method that wraps the ajax call like so:

    $("#search").kendoAutoComplete({
            dataTextField: "Name",
            minLength: 1,
            dataSource: {
                type: "json",
                serverFiltering: true,
                transport: {
                    read:
                        function(options) {
                            $.ajax({
                                url: "someUrl",
                                contentType: 'application/json',
                                data: { text: options.data.filter.filters[0].value },
                                type: "Get",
                                xhrFields: {
                                    withCredentials: true
                                },
                                crossDomain: true,
                                success: function (result) {
                                     options.success(result);
                                }
                            });
                        }
                    }
                }
            }
        });
    

    This gives you the ability to replace the default ajax behavior.