Altenatives to ej.DataManager to request url by GET

Hi,

How we may url request by GET,  without need to force extra parameters like it happens in JsonAdaptor and OdataAdaptor? 

In UrlAdaptor the method is post, is it possible to modify this?

To request url by GET, is it only possible using ej.DataManager?

Thanks again.

Example:
$("#viewLista").ejGrid({
dataSource: ej.DataManager({url : 'http://data.mapion.com.br/000_-_000_-_Informações_Imoveis', adaptor: new ej.JsonAdaptor( {options:{}})}),
headers: [{ "Range-Unit": "items", "Content-Range": '"' + pageSize-(pageIndex*pageSize) +'-'+ pageIndex*pageSize + '"', "Prefer": "count=exact" }],
allowScrolling: true,
allowFiltering: true,
allowPaging: true,
//query: new ej.Query(),
filterSettings: { filterType: "menu" },
contextMenuSettings: { enableContextMenu: true },
//offline: true,
//load: "load",
isResponsive: true,
pageSettings: { pageSize: pageSize, printMode: ej.Grid.PrintMode.AllPages },
toolbarSettings : { showToolbar : true, toolbarItems : [ej.Grid.ToolBarItems.PrintGrid,
//ej.Grid.ToolBarItems.ExcelExport, //M#66 - Ocultar Botões para exportação da grid - Plano para 2° versão
//ej.Grid.ToolBarItems.PdfExport, //M#66 - Ocultar Botões para exportação da grid - Plano para 2° versão
ej.Grid.ToolBarItems.Search]
},
columns: [
{ headerText: "Inscrição", width: 30 , height:20, headerTextAlign: "center", template:"<span class='inscricao'>{{:insc_munic}}</span>", priority: 1 },
{ field: "nome_g", headerText: "Proprietário", width: 80, priority: 2, headerTextAlign: "center" },
{ headerText: "Endereço", template:"<span>{{:tipo_logradouro_cnt+' '+logradouro_cnt}}</span>", width: 60, priority: 2, headerTextAlign: "center" },
{ field: "branco", headerText: "Uso", width: 20, priority: 2, headerTextAlign: "center" },
{ field: "", width: 17, headerText: "Foto", headerTextAlign: "center", tooltip: "Fotos Fachada",
commands: [
{ type: "details", buttonOptions: { text: "Foto Frontal", contentType: "imageonly", prefixIcon:"e-icon e-image_01", click:"setPhotoAction", textAlign:"center", visible:false }}
],
isUnbound: true
},
{ field: "", headerText: "Croqui", width: 17, headerTextAlign: "center", tooltip: "Croqui Imóvel",
commands: [
{ type: "details", buttonOptions: { text: "Croqui Digital",contentType: "imageonly", prefixIcon:"e-icon e-paste_01", click:"setCroquiAction", visible:false}}
],
isUnbound: true
},
{ field: "", headerText: "BCI", width: 17, headerTextAlign: "center", tooltip: "Ficha Cadastral",
commands: [
{ type: "details", buttonOptions: { text: "Imprimir Ficha",contentType: "imageonly", prefixIcon:"e-icon e-print_01", click:"setPrintAction", visible:false}},
],
isUnbound: true
},
{ field: "", headerText: "Mapa", width: 17, headerTextAlign: "center", tooltip: "Mapa",
commands: [
{ type: "details", buttonOptions: { text: "Mapa",contentType: "imageonly", prefixIcon:"e-icon e-image", click:"setMapAction", visible:false}}
],
isUnbound: true
}

],

recordClick: function (args) {
infoData = args.data;
if(actionSel==1){
vinculoCaracImovel(infoData['cód'], openPhoto);
}
else if (actionSel==2) {
vinculoCaracImovel(infoData['cód'], showDownload, 'CROQUI');
}
else if (actionSel==3) {
showPrint(infoData);
}
else if (actionSel==4) {
showMap();
}
else{
//Adicionado delay para concluir a função vinculoCaracImovel
vinculoCaracImovel(infoData['cód'], detalharArquivo, infoData);
}
actionSel = 0;
},
actionComplete: function (args) {
//Aplicar mascára para Inscrição estadual ao realizar a paginação
$('.inscricao').mask('00.00.000.0000.0000');
},
toolbarClick: function (args) {

if (args.itemName == "Print") {
args.cancel = true;

var gridObj = $("#viewLista").data("ejGrid");
gridObj.hideColumns("Foto");
gridObj.hideColumns("BCI");
gridObj.hideColumns("Mapa");
gridObj.hideColumns("Croqui");

//$("#viewLista").ejGrid("print");
gridObj.print();

gridObj.showColumns("Foto");
gridObj.showColumns("BCI");
gridObj.showColumns("Mapa");
gridObj.showColumns("Croqui");

}
if (args.itemName == "Excel Export") {
//M#66 - Ocultar Botões para exportação da grid - Plano para 2° versão
showMessage('Exportar para Excel');
//this.exportGrid = this["export"];
//this.export("api/Export/ExcelExport"); // Excel Export method.
args.cancel = true;
}
if (args.itemName == "PDF Export") {
//M#66 - Ocultar Botões para exportação da grid - Plano para 2° versão
showMessage('Exportar para Pdf');
args.cancel = true;
}

}

}).executeLocal(ej.Query());//.executeQuery(new ej.Query());//.executeLocal(ej.Query());

$("#paging").click(function () {
var query = ej.Query().page(
function () {
if($('#index').val() !=="") {
pageIndex =$('#index').val();
return pageIndex;
}
else
return 1;
},
function () {
if($('#size').val() !=="") {
pageSize =$('#size').val();
return pageSize;
}
else
return 2;
});

//var execute =
//$("#viewLista").ejGrid("ejGrid").executeLocal(query) // executing query
/*.done(function (e) {
$("#table1 tbody").html($("#tableTemplate").render(e.result));
});*/
});

7 Replies

SA Saravanan Arunachalam Syncfusion Team October 31, 2017 01:19 PM UTC

Hi Rodrigo, 
 
Thanks for contacting Syncfusion’s support. 
 
Yes, we can modify the UrlAdaptor based on our requirement by using customAdaptor. In customAdaptor, we can extend any existing adaptor and modify it based on our requirement. To know more about custom Adaptor kindly refer to the following UG documentation link: https://help.syncfusion.com/js/datamanager/data-adaptors#custom-adaptor  
In your case we can extend the UrlAdaptor to modify the processQuery method and make the request type to GET from POST. Kindly refer to the following code snippet.  
 
// Required internal methods methods used by process query  
  
var filterQueries = function (queries, name) {  
    return queries.filter(function (q) {  
        return q.fn === name;  
    }) || [];  
};  
var filterQueryLists = function (queries, singles) {  
    var filtered = queries.filter(function (q) {  
        return singles.indexOf(q.fn) !== -1;  
    }), res = {};  
    for (var i = 0; i < filtered.length; i++) {  
        if (!res[filtered[i].fn])  
            res[filtered[i].fn] = filtered[i].e;  
    }  
    return res;  
};  
var callAdaptorFunc = function (obj, fnName, param, param1) {  
    if (obj[fnName]) {  
        var res = obj[fnName](param, param1);  
        if (!isNull(res)) param = res;  
    }  
    return param;  
};  
var getValue = function (value, inst) {  
    if (typeof value === "function")  
        return value.call(inst || {});  
    return value;  
};  
var isNull = function (val) {  
    return val === undefined || val === null;  
};  
  
//Custom Adaptor to customize the existing Adaptor  
  
var customAdaptor =  new ej.UrlAdaptor().extend({  
    //overriding the process query method for customization  
    processQuery: function (dm, query, hierarchyFilters) {   
        var sorted = filterQueries(query.queries, "onSortBy"),  
            grouped = filterQueries(query.queries, "onGroup"),  
            filters = filterQueries(query.queries, "onWhere"),  
            searchs = filterQueries(query.queries, "onSearch"),  
            aggregates = filterQueries(query.queries, "onAggregates"),  
            singles = filterQueryLists(query.queries, ["onSelect", "onPage", "onSkip", "onTake", "onRange"]),  
            params = query._params,  
            url = dm.dataSource.url, tmp, skip, take = null,  
            op = this.options;  
  
        var r = {  
            sorted: [],  
            grouped: [],  
            filters: [],  
            searches: [],  
            aggregates: []  
        };  
  
        // calc Paging & Range  
        if (singles["onPage"]) {  
            tmp = singles["onPage"];  
            skip = getValue(tmp.pageIndex, query);  
            take = getValue(tmp.pageSize, query);  
            skip = (skip - 1) * take;  
        } else if (singles["onRange"]) {  
            tmp = singles["onRange"];  
            skip = tmp.start;  
            take = tmp.end - tmp.start;  
        }  
  
        // Sorting  
        for (var i = 0; i < sorted.length; i++) {  
            tmp = getValue(sorted[i].e.fieldName, query);  
  
            r.sorted.push(callAdaptorFunc(this, "onEachSort", { name: tmp, direction: sorted[i].e.direction }, query));  
        }  
  
        // hierarchy  
        if (hierarchyFilters) {  
            tmp = this.getFiltersFrom(hierarchyFilters, query);  
            if (tmp)  
                r.filters.push(callAdaptorFunc(this, "onEachWhere", tmp.toJSON(), query));  
        }  
  
        // Filters  
        for (var i = 0; i < filters.length; i++) {  
            r.filters.push(callAdaptorFunc(this, "onEachWhere", filters[i].e.toJSON(), query));  
  
            for (var prop in r.filters[i]) {  
                if (isNull(r[prop]))  
                    delete r[prop];  
            }  
        }  
  
        // Searches  
        for (var i = 0; i < searchs.length; i++) {  
            tmp = searchs[i].e;  
            r.searches.push(callAdaptorFunc(this, "onEachSearch", {  
                fields: tmp.fieldNames,  
                operator: tmp.operator,  
                key: tmp.searchKey,  
                ignoreCase: tmp.ignoreCase  
            }, query));  
        }  
  
        // Grouping  
        for (var i = 0; i < grouped.length; i++) {  
            r.grouped.push(getValue(grouped[i].e.fieldName, query));  
        }  
  
        // aggregates  
        for (var i = 0; i < aggregates.length; i++) {  
            tmp = aggregates[i].e;   
            r.aggregates.push({ type: tmp.type, field: getValue(tmp.field, query) });  
        }  
  
        var req = {};  
        req[op.from] = query._fromTable;  
        if (op.expand) req[op.expand] = query._expands;  
        req[op.select] = singles["onSelect"] ? callAdaptorFunc(this, "onSelect", getValue(singles["onSelect"].fieldNames, query), query) : "";  
        req[op.count] = query._requiresCount ? callAdaptorFunc(this, "onCount", query._requiresCount, query) :"";  
        req[op.search] = r.searches.length ? callAdaptorFunc(this, "onSearch", r.searches, query) : "";  
        req[op.skip] = singles["onSkip"] ? callAdaptorFunc(this, "onSkip", getValue(singles["onSkip"].nos, query), query) : "";  
        req[op.take] = singles["onTake"] ? callAdaptorFunc(this, "onTake", getValue(singles["onTake"].nos, query), query) : "";  
        req[op.where] = r.filters.length || r.searches.length ? callAdaptorFunc(this, "onWhere", r.filters, query) : "";  
        req[op.sortBy] = r.sorted.length ? callAdaptorFunc(this, "onSortBy", r.sorted, query) : "";  
        req[op.group] = r.grouped.length ? callAdaptorFunc(this, "onGroup", r.grouped, query) : "";  
        req[op.aggregates] = r.aggregates.length ? callAdaptorFunc(this, "onAggregates", r.aggregates, query) : "";  
        req["param"] = [];  
          
        // Params  
        callAdaptorFunc(this, "addParams", { dm: dm, query: query, params: params, reqParams: req });  
  
        // cleanup  
        for (var prop in req) {  
            if (isNull(req[prop]) || req[prop] === "" || req[prop].length === 0 || prop === "params")  
                delete req[prop];  
        }  
  
        if (!(op.skip in req && op.take in req) && take !== null) {  
            req[op.skip] = callAdaptorFunc(this, "onSkip", skip, query);  
            req[op.take] = callAdaptorFunc(this, "onTake", take, query);  
        }  
        var p = this.pvt;  
        this.pvt = {};  
  
        if (this.options.requestType === "json") {  
            return {  
                data: JSON.stringify(req),  
                url: url,  
                ejPvtData: p,  
                type: "GET",  //Changing request type from POST to GET  
                contentType: "application/json; charset=utf-8"  
            }  
        }  
        tmp = this.convertToQueryString(req, query, dm);  
        tmp =  (dm.dataSource.url.indexOf("?")!== -1 ? "&" : "/") + tmp;  
        return {  
            type: "GET",  
            url: tmp.length ? url.replace(/\/*$/, tmp) : url,  
            ejPvtData: p  
        };  
    },  
    processResponse: ej.UrlAdaptor.prototype.processQuery // To customize the received response, you can modify here  
});  
  
$("#viewLista").ejGrid({  
    dataSource: ej.DataManager({url : 'http://data.mapion.com.br/000_-_000_-_Informações_Imoveis', adaptor:new customAdaptor(),  
    headers: [{ "Range-Unit": "items", "Content-Range": '"' + pageSize-(pageIndex*pageSize) +'-'+ pageIndex*pageSize + '"', "Prefer": "count=exact" }],  
    allowScrolling: true,  
    allowFiltering: true,  
    allowPaging: true,  
      
    ..............................................  
  
}).executeLocal(ej.Query());//.executeQuery(new ej.Query());//.executeLocal(ej.Query());  

Regards, 
Saravanan A. 



RC Rodrigo Carrapeta November 8, 2017 05:18 PM UTC

Thank you so much for the amazing answer, Saravanan.

But when I try the code, returns the following error in console:

--------------------------------------------

Uncaught TypeError: Cannot read property 'filter' of undefined

    at a (ej.web.all.min.js:10)

    at i.processQuery (ej.web.all.min.js:10)

    at t.DataManager.executeLocal (ej.web.all.min.js:10)

    at loadGridviewUrl (mapion-sefinlg.js:467)

    at HTMLDocument. (mapion-sefinlg.js:15)

    at j (jquery-3.1.1.min.js:2)

    at k (jquery-3.1.1.min.js:2)

--------------------------------------------

Example Code: Attached file

--------------------------------------------



Attachment: codeexample_b3e7cde6.7z


RS Renjith Singh Rajendran Syncfusion Team November 9, 2017 05:04 PM UTC

Hi Rodrigo, 

We are working on your requirement with high priority. We will update further details on November 10, 2017. 

Until then we appreciate your patience. 

Regards, 
Renjith Singh Rajendran. 



RC Rodrigo Carrapeta November 9, 2017 08:28 PM UTC

Hi Renjith,

Thank you so much for the answer, I'll be waiting.

I'm sorry for all incovinience.

Regards.

Rodrigo Carrapeta de Souza



RS Renjith Singh Rajendran Syncfusion Team November 13, 2017 05:00 PM UTC

Hi Rodrigo,  
 
We are sorry for the inconvenience caused. 
 
We have checked the sample code, we suspect that you have missed to properly enclose the DataManager’s instance in the Grid control with parenthesis. Kindly refer to the following code. 
 
$("#viewListaLogra").ejGrid({  
    dataSource: ej.DataManager({  
            url : 'http://io.mapion.com.br/api/0.1-a/ProxyPostgRest/api/000_-_000_-_Logradouro', adaptor:new customAdaptor(),  
            headers: [{ "Range-Unit": "items", "Content-Range": '"' + pageSize-(pageIndex*pageSize) +'-' pageIndex*pageSize + '"', "Prefer":"count=exact" }],  
    }),  
    allowScrolling: true,  
    allowFiltering: true,  
  
. . . . . . . . . . . . . . . . . . . . . . . . .   
});  
 
We have also prepared a JSPlayground sample, please refer the link below, 
 
 
Regards,  
Renjith Singh Rajendran. 




RC Rodrigo Carrapeta November 13, 2017 08:59 PM UTC

Hi, Renjith.

Thank you for the answer, it was really helpful. But the problem with the filter property persist (even in jsplayground - http://jsplayground.syncfusion.com/f4oco21v ).

--------------------

Uncaught TypeError: Cannot read property 'filter' of undefined

    at a (ej.web.all.min.js:10)

    at i.processQuery (ej.web.all.min.js:10)

    at t.DataManager.<anonymous> (ej.web.all.min.js:10)

    at Object.success (ej.web.all.min.js:10)

    at i (jquery-3.1.1.min.js:2)

    at Object.fireWith [as resolveWith] (jquery-3.1.1.min.js:2)

    at A (jquery-3.1.1.min.js:4)

    at XMLHttpRequest.<anonymous> (jquery-3.1.1.min.js:4)

a @ ej.web.all.min.js:10

processQuery @ ej.web.all.min.js:10

(anonymous) @ ej.web.all.min.js:10

(anonymous) @ ej.web.all.min.js:10

i @ jquery-3.1.1.min.js:2

fireWith @ jquery-3.1.1.min.js:2

A @ jquery-3.1.1.min.js:4

(anonymous) @ jquery-3.1.1.min.js:4

XMLHttpRequest.send (async)

send @ jquery-3.1.1.min.js:4

ajax @ jquery-3.1.1.min.js:4

_makeRequest @ ej.web.all.min.js:10

executeQuery @ ej.web.all.min.js:10

_initDataSource @ ej.web.all.min.js:10

_checkDataBinding @ ej.web.all.min.js:10

_init @ ej.web.all.min.js:10

(anonymous) @ ej.web.all.min.js:10

n.fn.(anonymous function) @ ej.web.all.min.js:10

dataLoad @ mapion-sefinlg.js:316

success @ mapion-sefinlg.js:21

i @ jquery-3.1.1.min.js:2

fireWith @ jquery-3.1.1.min.js:2

A @ jquery-3.1.1.min.js:4

(anonymous) @ jquery-3.1.1.min.js:4

XMLHttpRequest.send (async)

send @ jquery-3.1.1.min.js:4

ajax @ jquery-3.1.1.min.js:4

(anonymous) @ mapion-sefinlg.js:13

j @ jquery-3.1.1.min.js:2

k @ jquery-3.1.1.min.js:2

setTimeout (async)

(anonymous) @ jquery-3.1.1.min.js:2

i @ jquery-3.1.1.min.js:2

fireWith @ jquery-3.1.1.min.js:2

fire @ jquery-3.1.1.min.js:2

i @ jquery-3.1.1.min.js:2

fireWith @ jquery-3.1.1.min.js:2

ready @ jquery-3.1.1.min.js:2

R @ jquery-3.1.1.min.js:3

--------------------------

Above I add all the libraries I call in the page. 

---------------------------

<link rel='nofollow' href="syncfusion/content/ejthemes/bootstrap-theme/ej.web.all.min.css" rel="stylesheet"/>

    <link rel='nofollow' href="syncfusion/content/default-responsive.css" rel="stylesheet"/>

    <link rel='nofollow' href="syncfusion/content/ejthemes/responsive-css/ej.responsive.css" rel="stylesheet"/>

    <!--[if lt IE 9]>

    <script src="syncfusion/scscripts/jquery-1.11.3.min.js"></script>

    <![endif]-->

    <!--[if gte IE 9]><!-->

    <script src="syncfusion/scripts/jquery-3.1.1.min.js"></script>

    <!--<![endif]-->

    <!--<script src="syncfusion/scripts/jquery.validate.min.js"></script>-->

    <!--<script src="syncfusion/scripts/jquery.validate.unobtrusive.min.js"></script>-->

    <script src="syncfusion/scripts/jsondata.min.js"></script>

    <script src="syncfusion/scripts/jsrender.min.js"></script>

    <script src="syncfusion/scripts/ej.web.all.min.js" type="text/javascript"></script>

    <script src="syncfusion/scripts/properties.js" type="text/javascript"></script>

------------------------

Do you think I forgot to add some JS at the begining of the file (I've been thinking if that was the reason for this error)?

Regarts,

Rodrigo C de Souza



RS Renjith Singh Rajendran Syncfusion Team November 14, 2017 12:55 PM UTC

Hi Rodrigo, 

We have analyzed the sample. We have modified the sample.  

Refer to the following link: http://jsplayground.syncfusion.com/n2v4risd 

After modify the sample, we faced the following t error. This occurs because of not passing the return value from server side as result and count with respect to the provided skip and take value.  
 
We could see that you are returning the entire data at the first page at server side. Please refer the screenshots below, 

 

Figure 1: Entire data is returned at the first page loading. 

 
Figure 2: Shows the skip and take value provided. 

Regards, 
Renjith Singh Rajendran. 


Loader.
Up arrow icon