How to send array with json using ajax - json

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

Related

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"

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

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.

Why is the update operation not posting any data?

I am using the Kendo Grid with inline editing. When I click the "Update" button, a POST gets made to my controller method with this signature. The controller action gets hit, so the POST is working.
[HttpPost]
public HttpResponseMessage SaveAccountAdmin(string jsonCompanyContacts)
However the POST data in the update operation never arrives - its always null.
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: {
jsonCompanyContacts: "John Doe"
}
},
Here is the FULL data source code.
var dataSource = new kendo.data.DataSource(
{
batch: false,
pageSize: 10,
transport: {
create: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json"
},
read: {
url: "/Company/ReadAccountAdmin"
},
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data: {
jsonCompanyContacts: "John Doe"
}
},
//destroy: {},
parameterMap: function (data, type) {
return kendo.stringify(data);
}
},
this doesnt work either:
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
//data: { "jsonCompanyContacts": kendo.stringify({ jsonCompanyContacts: "John Doe" }) }
data: { "jsonCompanyContacts": "John Doe" }
},
//destroy: {},
parameterMap: function (data, type) {
return kendo.stringify(data);
}
BUT THIS WORKS- WHY?
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
//data: { "jsonCompanyContacts": kendo.stringify({ jsonCompanyContacts: "John Doe" }) }
//data: { "jsonCompanyContacts": "John Doe" }
},
//destroy: {},
parameterMap: function (data, type) {
return kendo.stringify({ "jsonCompanyContacts": "John Doe" });
}
The value is not passed to the controller as a string. Try using a model. This might help: MVC3 & JSON.stringify() ModelBinding returns null model
UPDATE
You really don't want to do it like that. Might work in theis one case, but you are shooting yourself in the foot.
Model
public class CompanyContactModel
{
public string CompanyContacts { get; set; }
}
Controller Signature
public JsonResult SaveAccountAdmin(CompanyContactModel companyContactModel)
...
Better
public JsonResult SaveAccountAdmin([DataSourceRequest]DataSourceRequest request, CompanyContactModel companyContactModel)
...
Update and Return and put into List
If error: ModelState.AddModelError(string.Empty, e.Message);
DataSourceResult result = [Your Model List].ToDataSourceResult(request, ModelState);
return Json(result, JsonRequestBehavior.AllowGet);
}
Try doing this in your update definition:
update: {
url: "/Company/SaveAccountAdmin",
contentType: "application/json; charset=utf-8",
type: "POST",
dataType: "json",
data:{ "jsonCompanyContacts": kendo.stringify({ jsonCompanyContacts: "John Doe" })}
}
You might have to remove the operation in your parameterMap for this to work. The main thing is that you want to post a variable with the same name as in your controller. That variable should contain your stringified data.
You could also move this operation to your parameterMap if you want.
I had similar problem like you.I am getting values from the broswer , but its not posting the values to the update action model.
In my case I used "[ScriptIgnore(ApplyToOverrides = true)]" on the model which works fine.

how connect with web service

I am trying to get some data from a web service:
$.ajax({
type: 'POST',
url: "http://192.******.asmx?op=GetJSONString",
method: "serverCallback",
data: "Select con.cod as codigo, con.res as descripcion from con where ide>0",
success: function(data){alert(data)},
});
How can I get the returned JSON data?
Here is what my calls look like. Can you be more specific of the issue you are having?
$.ajax({
type: "POST",
data: "SOME DATA",
dataType: "json",
url : "/myapp/service.json",
cache: false,
error: function() {
alert("There was an issue");
}
,
success: function(data)
{
processJson(data);
}
});
I will also post what has worked with me for asmx services.
In the example below, for "url": "/service/Details.asmx/Reject", the "/Reject" is the method name in the web service (asmx) file.
$.ajax({
"dataType": 'json',
"contentType": "application/json; charset=utf-8",
"type": "POST",
"url": "/service/Details.asmx/Reject",
"data": "{\"itemId\":\"" + id + "\",\"comment\":\"" + comms + "\"}",
"success":
function (msg) {
alert("Yea it worked!");
});
}
});