DataTable retrieve json from dataSrc unknown parameter - html

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.

Related

Getting parserError when calling controller using ajax and set data in datatable in mvc project

I am working in mvc and i got the parserError when i call the controller using ajax and want to set list using datatable. but i don't know what i am doing wrong here.
when try to debug then i was not got my self in controller.
After i searched i found that use datatype:'text' but that don't want it.
I want only json data and want to set using data table.
but don't know what i doing wrong here.
Any one have idea, let me share here.
<div class="card-body">
<table id="userGrid" class="table table-bordered table-striped">
<thead>
<tr>
<th>Email</th>
<th>Password</th>
<th>Zipcode</th>
<th>IsAdmin</th>
<th>IsFirstTimeLoggedIn</th>
</tr>
</thead>
</table>
</div>
#section Scripts{
<script type="text/javascript">
$(function () {
$.ajax({
type: "POST",
url: "/User/UserList",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert("failure:"+response.d);
},
error: function (response, jqXHR, textStatus, errorThrown) {
debugger
alert("Error:"+response.d);
}
});
});
function OnSuccess(response) {
$("#userGrid").DataTable(
{
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
"responsive": true,
"serverSide": true,
"processing":true,
data: response,
columns: [{ "data": "Email" },
{ "data": "Password" },
{ "data": "Zipcode" },
{ "data": "IsAdmin" },
{ "data": "IsFirstTimeLoggedIn" }]
});
};
</script>
}
public ActionResult UserList()
{
try
{
List<User> users = _userService.GetAllUsers().ToList();
return Json(new { data = users }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
_log.ErrorFormat("Error in get user list. Error : {0}", ex.Message);
_log.Error(ex);
throw;
}
}
I want only json data and want to set using data table
Since the json format returned by the UserList method contains data before the users , you need to obtain the returned data collection through response.data in the success method of ajax.
On the other hand, because you get the data in the success method (not directly through ajax), you need to comment out the "serverSide": true statement.
Here is the example:
function OnSuccess(response) {
$("#userGrid").DataTable(
{
"paging": true,
"lengthChange": false,
"searching": false,
"ordering": true,
"info": true,
"autoWidth": false,
"responsive": true,
// "serverSide": true,
"processing":true,
data: response.data,
columns: [{ "data": "Email" },
{ "data": "Password" },
{ "data": "Zipcode" },
{ "data": "IsAdmin" },
{ "data": "IsFirstTimeLoggedIn" }]
});
};
Here is the test result:

put the dynamic data in dropdown list using select2.js

I am tried to get the data from my file using ajax in select2.js. I want to get data according the value which I entered in my textbox and append that value in my dropdown using select2. I tried for that but it didn't give the result according my search keyword how to solve these problem.
Here is my input box on HTML:
<input type="text" id="Address1" name="Address1" >
Javascript Code
<script>
$("#Address1").select2({
tags: [],
ajax: {
url: 'ajaxhandler.php',
dataType: 'json',
type: "POST",
// quietMillis: 50,
data: function (term) {
return {
term: term
};
},
results: function (term) {
}
}
});
</script>
ajaxhandler.php
<?php
$CITIES = array("Ahmedabad", "Mumbai", "USA", "Canada", "Pune");
echo json_encode($CITIES); exit;
?>
Data format for Select2.js (version 4) is:
{
"results": [
{
"id": 1,
"text": "Option 1"
},
{
"id": 2,
"text": "Option 2"
}
]
}
See: https://select2.org/data-sources/formats
So you need to processResults received form server like below:
processResults: function (data) {
return {
results: $.map(data.items, function(obj, index) {
return { id: index, text: obj };
})
};
},
Here is a fiddle: http://jsfiddle.net/beaver71/cwb9r23b/

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);
}
});

How to send array of objects to a controller method?

I need your help, I have this piece of code in the controller side
public bool DraftMessage(message[] draftMessages, HttpPostedFileBase[] files = null)
{
return true;
}
and I use this client side code to send the data
function DraftMessage()
{
var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }]
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage","Activities")",
datatype: "json",
traditional: true,
data: JSON.stringify({ draftMessages: myArray }),
beforeSend: function () { }
}).done(function (data) {});
}
$("input, select, textarea").change(function () { DraftMessage(); });
var contents = $('.note-editable').html();
$(".compose-message").on("blur", ".note-editable", function () {
if (contents != $(this).html()) {
DraftMessage();
contents = $(this).html();
}
});
but when I debug it I found that the array of messages in the controller is null so could anyone guide me about what I did wrong and help me to fix this issue.
You need to set contentType as "application/json"
function DraftMessage() {
var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }];
$.ajax({
type: "POST",
url: "#Url.Action("DraftMessage","Home")",
contentType: "application/json",
data: JSON.stringify({ draftMessages: myArray })
}).done(function (data) {
console.log(data);
});
}
The default value of contentType header is "application/x-www-form-urlencoded" . Since we are sending the json stringified version of a a complex data structure, we should explicitly specify the contentType

Bind kendo.data.datasource json data to kendo listview

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);
}
});