How to send array of objects to a controller method? - json

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

Related

Update Chart.js data with ajax

I want to update my chart with ajax and Flask but
I can not update the data:
var chart = new Chart(canvas, {
type: "line",
datasets: [{
label: 'My Dataset',
}]
})
$(document).ready(function () {
$.ajax({
dataType: "text",
contentType: "application/json",
url: '{{ url_for("data_page") }}',
type: "post",
data: JSON.stringify({
timeDelta: "7",
technologie: "Java",
}),
success: function (data) {
let json = $.parseJSON(data); ==> [["2021-06-04", "2021-06-05"],[47, 3]]
chart.data.labels.push(json[0]); ==> It seems to work
chart.data.datasets[0].data = json[1]; ==> here I get : "Cannot set property 'data' of undefined"
chart.update();
}
});
});
I don't understand ,
where am I wrong ?
Thanks for any help !
It doesn't work because you initially create the chart with wrong configuration. The labels and datasets arrays must be contained in a data object.
Try this instead:
var chart = new Chart(canvas, {
type: 'line',
data: {
labels: [],
datasets: [{
label: 'My Dataset',
data: []
}]
}
});

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

Assign array of strings from JSON to Handsontables object in javascript?

I am trying to assign array of string to handsontables column as auto-complete. I am getting this JSON data from AJAX calls.
I am not getting to assign to source:. Please follow the code.
var loadBU = function(data) {
$.ajax({
url: "/EditInitiatives.svc/GetBUData",
data: "clientId=" + $value.val(),
type: "GET",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
data(res);
},
error: function (error) {
alert("Error: " + error.responseText);
}
});
};
$("#example2").handsontable({
data: getCarData(),
startRows: 7,
startCols: 4,
columns: [
{ data:'BusinessUnit',
type:'autocomplete',
source:loadBU(function(output){
var results = output.d
var arr = [], item;
for (var i = 0, len = results.length; i < len; i++) {
item = results[i];
arr.push([[item]]);
}
return arr;
}),
strict: true
},
]
});
It suppose to be like that EX: source: ["yellow", "red", "orange", "green", "blue", "gray", "black", "white"],
I don't understand how to assign array to source.
Reference
Your "return arr;" does not return to the "source:", it returns to the "loadBU" function.
For example, you could do:
success: function (res) {
var arr = data(res);
},
This is why it is not being assigned.
Try making your Ajax call before $("#example2").handsontable({ and save it to someVariable, then set the source: someVariable
Depending on what your Ajax call returns, you may also need to make some manipulations. For example, I needed to loop through and load into an array:
function AppendToArray(ajaxValues, theArray) {
for (var i = 0; i < ajaxValues.length; i++) {
theArray.push('' + ajaxValues[i].Text + '');
}
}
I hope this helps
I use it like this:
var workers = null;
$.ajax({
url: siteUrl + "/Worker/Get",
dataType: 'json',
type: 'GET',
cache: false
})
.done(function (data) {
$("#worker-grid").handsontable({
data: data,
rowHeaders: true,
colHeaders: ["internal<BR />identification", "name", "mobile", "e-mail address", "national<BR />identification", "partner", "source"],
colWidths: [100, 150, 100, 250, 150, 150, 100],
columns: [
{ data: "intId" },
{ data: "name" },
{ data: "mobile" },
{ data: "mail" },
{ data: "extId" },
{
data: "partner", type: 'dropdown', source: function (query, process) {
$.ajax({
url: siteUrl + "/Partner/Get",
dataType: 'json',
type: 'GET',
cache: false
})
.done(function (data) {
var values = [];
for (i in data) values.push(data[i].name);
process(values);
});
}
},
{ data: "source" }
],
columnSorting: true,
minSpareRows: 1
});
workers = $("#worker-grid").data("handsontable");
});
The key in assigning to the source is the process parameter in the source function.
I would like to add however that this approach will be fetching data from the server with every use. My example above uses a dropdown which does not make sense.. But it's the correct approach when using with autocompletion.

Ajax post data store with json and jsonData

i want to write a data store, that gets its data by an ajax call. The ajax call has to be a http post message and has to contain some data in json format.
Thats what I have so far:
Ext.define("MyApp.store.FileContent", {
extend: "Ext.data.Store",
model:'MyApp.model.FileContent',
autoLoad: true,
proxy: {
actionMethods : {
read : 'POST'
},
type: 'ajax',
defaultHeaders:{
'Content-Type': 'application/json; charset=utf-8',
},
url : apiUrl + 'Files/GetFileInfo',
jsonData : '{"file": "myfile"}'
}
});
The call to the webservice works, but the variable "file" is always empty. What is wrong here?
Got it by writing a custom proxy
store:
Ext.define("MyApp.store.FileContent", {
extend: "Ext.data.Store",
model:'MyApp.model.FileContent',
autoLoad: true,
requires: ['MyApp.proxy.FileContent'],
proxy: {
type: 'FileContent'
}
});
proxy:
Ext.define('MyApp.proxy.FileContent', {
extend: 'Ext.data.proxy.Proxy',
alias: 'proxy.FileContent',
create: function (operation, callback, scope) {
//Here goes your create logic
},
read: function (operation, callback, scope) {
Ext.Ajax.request({
url: apiUrl + 'Files/GetFileInfo',
method: "POST",
defaultHeaders:{
'Content-Type': 'application/json; charset=utf-8',
},
jsonData: '{"file": "myfile"}',
success: function(response){
var json = JSON.parse(response.responseText);
},
failure: function(){
alert("fail");
}
});
},
update: function (operation, callback, scope) {
//Here goes your update logic
},
destroy: function (operation, callback, scope) {
//Here goes your delete logic
}
});