Bind kendo.data.datasource json data to kendo listview - json

Category1 works but category doesn't. Both have same data. But category is a json response.
category is
{
"d": [
{"__type": "MenuData+Category", "id": 1, "name": "drinks"},
{"__type": "MenuData+Category", "id": 2, "name": "fruits"}
]
}
Do I remove the d. If so how do i do it? If not whats wrong?
<div id="categories" data-role="view" data-title="Categories">
<header data-role="header">
<div data-role="navbar">
<span data-role="view-title"></span>
</div>
</header>
<ul id="Ul1"
data-role="listview"
data-source="category" [NOTE: Changing this datasource to category1 works]
data-template="categories-template"
data-style="inset">
</ul>
</div>
<script id="categories-template" type="text/x-kendo-template">
#: name #
</script>
<script>
var app = new kendo.mobile.Application(),
category = new kendo.data.DataSource({
serverFiltering: true,
transport: {
read: {
type: "POST",
url: "http://localhost:60143/Mobile/Menu/MenuData.asmx/getCategory",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (xhr, ajaxOptions, thrownError) {
alert("error " + xhr.responseText);
}
},
schema: {
data: "d"
},
type: "json",
parameterMap: function (options) {
return JSON.stringify(options);
}
}
}),
category1 = new kendo.data.DataSource({
data: [
{ id: 1,name: "Fruits" },
{ id: 2,name: "Drinks" },
]
});
</script>

You have placed schema inside transport definition while it is member of DataSource.
Try:
category = new kendo.data.DataSource({
serverFiltering: true,
transport : {
read: {
type : "POST",
url : "http://localhost:60143/Mobile/Menu/MenuData.asmx/getCategory",
contentType: "application/json; charset=utf-8",
dataType : "json",
error : function (xhr, ajaxOptions, thrownError) {
alert("error " + xhr.responseText);
}
}
},
schema : {
data: "d"
},
type : "json",
parameterMap : function (options) {
return JSON.stringify(options);
}
});

Related

Update item in another site collection in sharepoint 2013

I need to update item in another site collection according to this article I make my code like this
<script type="text/javascript">
$(document).ready(function () {
var otherSiteUrl = "<sitecollectionurl>";
var listName = "TestList";
var itemType = GetItemTypeForListName(listName);
var item = {
"__metadata": {
"type": itemType
},
"Title": "updated title"
};
$.ajax({
url: otherSiteUrl + "/_api/contextinfo",
type: "POST",
headers: {
"Accept": "application/json;odata=verbose"
},
success: function (contextData) {
alert(contextData.d.GetContextWebInformation.FormDigestValue);
$.ajax({
url: otherSiteUrl + "/_api/web/lists/getbytitle('" + listName + "')/items?#target='" + otherSiteUrl + "'",
method: "POST",
contentType: "application/json;odata=verbose",
data: JSON.stringify(item),
async: false,
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue
},
success: function (data) {
alert('success');
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error');
}
});
});
function GetItemTypeForListName(name) {
return "SP.Data." + name.charAt(0).toUpperCase() + name.split(" ").join("").slice(1) + "ListItem";
}
</script>
I used
"X-RequestDigest":
contextData.d.GetContextWebInformation.FormDigestValue
after that I chenge ajax header like
"X-RequestDigest":
$("#__REQUESTDIGEST").val(contextData.d.GetContextWebInformation.FormDigestValue)
for both RequestDigest I got this error:
Invalid JSON. A token was not recognized in the JSON content
after that I chenge ajax header as
How can I update item successfully in another site collection with api?
eventually, I can edit item in another site collection.I just little change in my code.
first, most important part is library full name dose not contain List I use this url to find out library full name .
[Site url]/_api/web/lists/GetByTitle('List Name')/ListItemEntityTypeFullName
then I change metadate as
"__metadata": { "type": 'SP.Data.DocumentsItem' },
second I added
"X-HTTP-Method": "MERGE" , "If-Match": "*"
to header like:
headers: {
"Accept": "application/json;odata=verbose",
"X-RequestDigest": contextData.d.GetContextWebInformation.FormDigestValue,
"X-HTTP-Method": "MERGE",
"If-Match": "*"
},

Try loading data from JSON using JsGrid MVC

I have a problem loading data from JSON, when i assign the JSON to property "data" of JsGrid there are not data found in the table. I am retriving the data using Ajax.
$.ajax({
url: '#Url.Action("consulta_Unidades")',
async: false,
type: 'POST',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (response) {
//console.log(response.value);
datos = JSON.stringify(response);
alert(datos);
}
});
The JsGrid code is next.
$("#table_div").jsGrid({
width: "100%",
height: "auto",
editing: true,
data: datos,
fields: [
{ name: "id_almacen", type: "text", width: 150 },
{ name: "idunidad", type: "text", width: 150 },
{ name: "tipo_unidad", type: "text", width: 150 },
{ name: "nomenclatura ", type: "text", width: 150 },
{ name: "capacidad_tarimas", type: "text", width: 150 },
{ name: "altura", type: "text", width: 150 },
{ type: "control" }
]
});
Any idea for resolve this problem?
In your ajax success "response" its a json object, only check
if(response){
datos=response
}
Another scenario:
The property "data" should be a "object" like json.
Change
datos = JSON.stringify(response);
For
datos = JSON.parse(response);
Use
datos = JSON.parse(JSON.stringify(response));
Only if it required for object "response"

DataTable retrieve json from dataSrc unknown parameter

I have a problem when population results from my ajax to datatables, i already verified that my ajax function works and return results
Here is my javascript code:
function getBookingRecords() {
tblDirectLoanReceipt = $('#tbBooking').DataTable();
tblDirectLoanReceipt.destroy();
tblDirectLoanReceipt = $('#tbBooking').DataTable({
autoWidth: true,
initComplete: function () {
},
processing: true,
serverSide:true,
ajax: {
type: 'post',
contentType: 'application/json; charset=utf-8',
url: '/Booking/RetrieveBookingRecords',
dataSrc: function (json) {
console.log(json);
return json;
},
columns: [
{ data: 'dsm_description' },
{ data: 'code' }
]
}
});
}
and my html code:
#section Scripts
{
#Helper.LoadCustomJS("ViewsJS/Booking/JS_Booking.js", Url)
}
<div class="row">
<div class="col-md-12">
<div class="table-responsive">
<table id="tbBooking">
<thead>
<tr>
<th>dsm_description</th>
<th>code</th>
</tr>
</thead>
<tbody></tbody>
</table>
</div>
</div>
</div>
How can i possibly fix this issue? What am i missing? thanks for any help in advance :)
update:
Error result
You should try to make sure your returned json data from ajax be formated like the following
{
"data": [
{
...
"dsm_description": "Sample description 1",
"code": "Sample code 1",
...
},
{
...
"dsm_description": "Sample description 2",
"code": "Sample code 2",
...
}]
}
To format returned json data, you could try to use library JSON.NET
var listData = new List<Dictionary<string,object>>();
....
var result = new {Data = listData};
return Content(JsonConvert.SerializeObject(result), "application/json");
Could you try this:
function getBookingRecords() {
tblDirectLoanReceipt = $('#tbBooking').DataTable();
tblDirectLoanReceipt.destroy();
tblDirectLoanReceipt = $('#tbBooking').DataTable({
autoWidth: true,
initComplete: function() {},
processing: true,
serverSide: true,
ajax: {
type: 'post',
contentType: 'application/json; charset=utf-8',
url: '/Booking/RetrieveBookingRecords',
dataSrc: "",
columns: [{
data: 'dsm_description'
}, {
data: 'code'
}]
}
});
As per my comment.
Note that if your Ajax source simply returns an array of data to
display, rather than an object, set this parameter to be an empty
string.
Hope that helps.

How to send array with json using ajax

How do I send an array with json using ajax? I want to store email and name:
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: 'email=' + $('#txtemail').val() ,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});
Let's suppose you have an array?
var array = [
"student1" : {
"name": "jon",
"email": "test#example.com"
},
"student2" : {
"name": "jon2",
"email": "test2#example.com"
}
]
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array),
datatype : 'application/json',
}, function(success) {
console.log(success)
});
Your question is not clear.please write your question in correct format.then community can be resolve your question easily.
I assume your problem and give solution for that.
var array = {name:'dua',email:'dua#gmail.com'};
$.post('index.php?route=module/newsletters/news', {
data : JSON.stringify(array)
}, function(success) {
console.log(success)
});
var postData = { "email":email,"name":name }
$.ajax({
url: 'index.php?route=module/newsletters/news',
type: 'post',
data: postData,
dataType: 'json',
success: function(json) {
alert(json.message);
}
});

No HTTP resource was found that matches the request URI 'http://localhost:xxx:

I am working on .net web api.....
Web Api Config :
public static void Register(HttpConfiguration config)
{
// Verb Routing
RouteTable.Routes.MapHttpRoute(
name: "SmallBizApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new
{
id = RouteParameter.Optional,
action = RouteParameter.Optional
}
);
config.Formatters.Clear();
config.Formatters.Insert(0, new SmallBiz.WebAPI.Common.JsonpFormatter());
}
I am using jsonp format to load data in kendo-ui Gantt chart as can be seen...
<div id="grid"></div>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function () {
var projectdata = "http://localhost:1799/api",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: projectdata + "/project",
dataType: "jsonp"
},
update: {
url: projectdata + "/project/put",
dataType: "jsonp"
},
destroy: {
url: projectdata + "/project/delete",
dataType: "jsonp"
},
create: {
url: projectdata + "/project/post",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProjectId",
fields: {
ProjectId: { editable: false, nullable: false },
Name: { validation: { required: true } },
Status: { validation: { required: true } },
IsActive: { type: "boolean" }
}
}
}
});
$("#grid").kendoGrid({
dataSource: dataSource,
pageable: true,
toolbar: ["create"],
scrollable: false,
sortable: true,
groupable: true,
columns: [
{ field: "Name", title: "Project Name", width: "170px" },
{ field: "Status", title: "Status", width: "110px" },
{ field: "IsActive", title: "Active", width: "50px" },
{ command: ["edit", "delete", "Setting","Task"], title: " ", width: "150px" }
],
editable: "popup"
});
});
</script>
Controller code :
public IQueryable<ProjectsDM> GetProject()
{
return db.Project;
}
[HttpPut]
public IHttpActionResult PutProjectsDM(int id, ProjectsDM projectsdm)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (id != projectsdm.ProjectId)
{
return BadRequest();
}
db.Entry(projectsdm).State = EntityState.Modified;
try
{
projectsdm.ModifiedBy = "adnan";
projectsdm.ModifiedDate = DateTime.Now;
db.SaveChanges();
}
catch (DbUpdateConcurrencyException)
{
if (!ProjectsDMExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return StatusCode(HttpStatusCode.NoContent);
}
Get method/action is working fine in kendo grid but i face problem
with put method/action(when we try to edit some record in grid)....
The errors in firebug .net tab
Response : "Message": "No HTTP resource was found that matches the
request URI 'http://localhost:1799/api/project
/put?callback=jQuery191012879030621062526_1433486934717&models=[{\"ProjectId\":2%2C\"ClientId\":1%2C
\"FirmId\":1%2C\"Status\":\"Started\"%2C\"Name\":\"Flexi77\"%2C\"IsActive\":true%2C\"CreatedDate\":\"2015-06-03T00
:00:00\"%2C\"ModifiedDate\":\"2015-06-03T00:00:00\"%2C\"CreatedBy\":\"adnan\"%2C\"ModifiedBy\":\"adnan
\"}]&_=1433486934719'.",
> "MessageDetail": "No action was found on the controller 'Project'
that matches the name 'put'."
json : "No action was found on the controller 'Project' that matches
the name 'put'."
Is there some route error or stupid mistake, please do help....
any kind of hint/help is much appreciated....
thanks for your time
The problem is that your Web API action expects two parameters:
int id, it's missing from the request URL
ProjectsDM projectsdm, can be retrieved from the payload (request body)
You need to use an URL that includes the missing id parameter. In the route template it's optional, but, if it's missing, as the action which requires it, the action cannot be chosen by the action selector.
So either add the id to the URL, or remove the id parameter from the action.