How to send Select2 AJAX POST with body? - javascript

I am using select2 with ajax. The data needs to be fetched using a POST request with some payload in the body.
POST request is being sent but the data is urlencoded and sent as request payload instead of request body.
I am trying this:
self.$("#elem-id").select2({
placeholder: 'Placeholder Text',
allowClear: true,
ajax: {
type: 'POST',
url: 'my_url',
dataType: 'json',
data: function(term, page) {
return {
q: term,
q2: [{
"hello": "world"
}]
};
},
params: {
headers: getHeaders(),
contentType: "application/json"
},
quietMillis: 250,
results: function(data, page) {
return {
.....
};
},
cache: true
}
});

Pass the object you return in the done function through JSON.stringify function
data: function(term, page) {
return JSON.stringify({
q: term,
q2: [{
"hello": "world"
}]
});
},

Related

JS Datatable not displaying AJAX response

Datatable is not displaying the response of an AJAX call to flask backend.
The data is retrieved as I can see it in the console.log of the success field of the AJAX call, however its not populating in the table.
Here is the JSON:
{'events':
[
{
'TIME': 'Evening',
'DESCRIPTION': 'test1'
},
{
'TIME': 'Morning',
'DESCRIPTION': 'test2'
}
]
}
This is the JS part:
function load_table() {
var payload = {'from_date': $('#from_date').val(), 'to_date': $('#to_date').val()}
$('#table').DataTable({
pageLength: 50,
paging: true,
ajax: {
url: "data/get-events/" + JSON.stringify(payload),
dataType: "json",
type: 'GET',
error: function(e){
alert(e);
},
success: function(e){
console.log(e);
},
dataSrc: 'events'
},
columns: [
{ title: 'Time', data: 'TIME'},
{ title: 'Event', data: 'DESCRIPTION'}
],
bDestroy: true,
});
}
I tried the tens of answers to my similar question but none of them worked.

Add new object to fullcalendar from Ajax

I am trying to add new events from an ajax to fullcalendar events
Here is what I've tried
$.ajax({
type: 'GET',
url: 'ajax link',
headers: {
dateType: "json",
"Authorization":"something"
},
dataType: "json",
success: function (res){
var wow = res;
}
})
var EventsField = {
id: 1,
events: [
{
id: '1',
start: curYear+'-'+curMonth+'-08T08:30:00',
end: curYear+'-'+curMonth+'-08T13:00:00',
title: 'Some Title',
backgroundColor: '#bff2f2',
borderColor: '#00cccc',
description: 'Some text'
},
]
};
So, from ajax I get variables like the ones present in the events object, and I want to get those from ajax and put them into the events objects.
Thanks!

Kendo grid row disapeared when editing after adding a row

I defined a kendo grid like that, and somehow after adding a row, the first edit click I do (before sending to the server) the row I just added is disappearing, and after refreshing its still there.
any suggestions why its happening?
$("#actionGrid").kendoGrid({
scrollable: true,
height: "200px",
toolbar: [{name: "create", text: "Add"}],
editable: {
mode: "inline",
confirmation: false
},
columns: [
{ field: "order", title: "Order", width: 80 },
{ field: "action", title: "Action name"},
{ command: ["edit", "destroy"], width: 100 }
],
dataSource: {
schema: {
model: {
id:"taskId",
fields: {
taskId: { type:"number" },
order: { type: "number", validation: { min: 0 } },
action: {}
}
}
},
transport: {
read: {
dataType: "json",
type: "GET",
contentType: "application/json",
url: "action/readByPId?pId=" + pId
},
destroy: {
dataType:"json",
type:"POST",
contentType:"application/json",
url: "action/delete"
},
update: {
dataType: "json",
type: "POST",
contentType: "application/json",
url: "action/update"
},
create: {
dataType: "json",
type: "POST",
contentType: "application/json",
url: "action/update"
},
parameterMap:function parameterMap(options,type) {
if(type !== "read"){
return JSON.stringify(options);
}
}
},
sort: { field: "order", dir: "asc" }
}
});
Kendo Grid have straight rules .Like whenever create new record ,have to return updated list to client side call . please make sure whether that updated record is returning or not.
IF you doing online offline feature of kendo UI . then follow this following demo.
https://demos.telerik.com/kendo-ui/grid/offline
you have not mentioned the data communication method . but if you are doing purly custom way then you have to update datasoure after doing any operation .Please put following code to get update with new data .
$('#GridName').data('kendoGrid').dataSource.read(); <!-- first reload data source -->
$('#GridName').data('kendoGrid').refresh(); <!-- refresh current UI -->

kendo grid delete button doesn't trigger delete function

Here is my grid:
$("#category-gridview").kendoGrid({
dataSource: {
type: "json",
transport: {
read: {
url: function (options) {
return '/Product/GetCategories?id=' + $("#selectedProductId").val() + '&company=' + $("#company-dropdown").val() + '&language=' + $("#country-dropdown").val();
},
dataType: "json",
type: "POST"
},
destroy: {
url: '/Product/DeleteProductCategory',
dataType: "json",
type: "POST",
contentType: "application/json"
},
parameterMap: function (options, operation) {
console.log("HÄÄR");
console.log(options);
if (operation !== "read" && options.models) {
return JSON.stringify({
category: options
});
}
}
},
schema: {
model: {
fields: {
id: {
type: "string"
},
name: {
type: "string"
},
}
}
},
},
columns: [{
field: "id",
hidden: true
}, {
field: "name",
title: "Category",
width: "30px"
}, {
command: "destroy",
title: " ",
width: 15
}],
editable: false,
});
somehow the read function works as expected but when i press the delete button i won't even reach my parameter map function.
When i look in chrome console there is no request sent to my controller.
here is my controller method:
[HttpPost]
public JsonResult DeleteProductCategory(CategoryResponse category)
{
return Json(category);
}
Let me try to answer, but to note that i change your transport and the column setting to match the field using kendo because obviously i can't use yours. Similar to this
transport: {
read: {
url: "http://demos.telerik.com/kendo-ui/service/products",
dataType: "jsonp"
},
destroy: {
url: "http://demos.telerik.com/kendo-ui/service/products/destroy",
dataType: "jsonp"
},
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return {models: kendo.stringify(options.models)};
}
}
},
At first glance i notice you use "POST" on read and delete call, actually you don't need them?
But then you said that you couldn't reach the parametermap, i came to
think of
You set editable : false, how can you edit it if you
set it to false? you should make it to editable : true(note: also you can try to set it to false and then you can see the delete function will not work)
DEMO
Instead of stringifing {param:value} Simply stringify value i.e stringify(options.models) for parameter category
parameterMap: function(options, operation) {
if (operation !== "read" && options.models) {
return { category: kendo.stringify(options.models) };
}
}

kendo ui crud operations using only jquery and Ajax

I am developing a web application which deals with interactive grids. I am using Kendo UI for displaying grids and doing CRUD operations. I am new to Kendo UI. We are performing database calls using jquery, Ajax only. I was able to make it read the data from the database and display it. But I am stuck at CRUD operations. How to get the event that a specific row or a specific single data is changed and perform the update. Please help me to understand how to do the crud operations. I couldn't find it in detail anywhere. There are 8 parameters which are in the first column. The user should be able to change the rest of the data except the parameters.
following is the code for Grid. CreateWBDGridData triggers the database service call and creates the table. gridSource is JSON data getting from the database after converting through Json convert function.
$(document).ready(function()
{
var param ="HOLE_DIAMETER|4.875_CASING_ID|5.5_GRAVEL_PACK|NET_PERF_THICKNESS|PERF_DIAMETER|PERF_GRAVEL_PERM_#19k|GRAVEL_BETA_FACTOR_#19K|SHOT_DENSITY";
$.when(GetWBDGridDataByWell(param)).then(function (data) {
});
});
function CreateWBDGridData(gridSource) {
if (gridSource == undefined) return;
console.log(gridSource);
$("#grid").kendoGrid({
dataSource: {
data: gridSource,
schema: {
model: {
fields: {
ParameterName: { type: "string" },
Zone_1: { type: "number" },
Zone_2: { type: "number" },
Zone_3: { type: "number" },
}
}
},
// pageSize: 20
},
//height: 550,
//scrollable: true,
//sortable: true,
//filterable: true,
//reorderable: true,
resizable:true,
//pageable: {
// input: true,
//numeric: false
//},
columns: [
{ field: "ParameterName", title: "Lucius 01", width: 300 },
{ field: "Zone_1", title: "Zone 1", width: 100 },
{ field: "Zone_2", title: "Zone 2", width: 100 },
{ field: "Zone_3", title: "Zone 3", width: 100 },
]
});
}
Controller
var dspstore = "System.Sources.Db.MsSql.DSPStore";
function GetWBDGridData(queryName, param) {
var varData = CreateParamQuery(dspstore, queryName, param);
CallService(GetWBDGridDataCompleted, varData);
}
var GetWBDGridDataCompleted = function (result) {
if (varDataType == "json") {
var myItems = $.parseJSON(result.GetDataItemsResult);
CreateWBDGridData(myItems);
}
}
Service call
function CallService(ServiceCompleted, varData) {
$.support.cors = true;
$.ajax({
context: this,
disableCaching: false,
headers: {
"Access-Control-Allow-Origin": '*',
'Accept': 'application/json',
'Content-Type': 'application/json'
},
type: varType, //GET or POST or PUT or DELETE verb
url: varUrl, // Location of the service
data: varData, //Data sent to server
//contentType: varContentType, // content type sent to server
dataType: varDataType, //Expected data format from server
processdata: varProcessData, //True or False
success: function (msg) {//On Successfull service call
ServiceCompleted(msg);
},
error: ServiceFailed// When Service call fails
});
}
Ok, as I Understand there 8 parameters which are the first column, have had has 3 more items which user can edit if so do as below.
$("#grid").kendoGrid({
dataSource: {
transport: {
read: function (options) {
$.ajax({
url: "/Your Controller/your read Action",
dataType: "json",
cache: false,
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
},
update: function (options) {
$.ajax({
url: "/Your Controller/your Update Action",
dataType: "json",
cache: false,
data:{model:options.data.models},
success: function (result) {
options.success(result);
},
error: function (result) {
options.error(result);
}
});
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
schema: {
model: {
fields: {
ParameterName: { type: "string",editable: false },
Zone_1: { type: "number",editable: true, validation: { required: true } },
Zone_2: { type: "number",editable: true, validation: { required: true } },
Zone_3: { type: "number" ,editable: true, validation: { required: true }},
}
}
},
pageSize: 10
},
resizable:true,
columns: [
{ field: "ParameterName", title: "Lucius 01", width: 300 },
{ field: "Zone_1", title: "Zone 1", width: 100 },
{ field: "Zone_2", title: "Zone 2", width: 100 },
{ field: "Zone_3", title: "Zone 3", width: 100 },
]
});
}
Use the model to specify the editable and non-editable fields and Your Data Source Data parameter does not use unless you're doing local calls, to do server calls call it as a function as shown above.
and your Controller action should look like below : (I Assume your using MVC)
[HttpGet]
public ActionResult ReadGridJson()
{
return Json(yourlist, JsonRequestBehavior.AllowGet);
}
[HttpGet]
public ActionResult UpdateGridJson(YourModelType model)
{
//update the DB and return the updated item
return Json(updateItem, JsonRequestBehavior.AllowGet);
}
Hope this helps, For more info check out the API DOC http://docs.telerik.com/kendo-ui/api/web/grid

Categories

Resources