i have a working ajax function with web method without getting string[] address or any other array string [] abc , in parameter , My arrays within array is
MDate: "04-08-2015"
MPurpose: 1
MTime: "1010"
RowNumber: 2
address: Array[1]
cell: Array[1]
company: Array[1]
designation: Array[1]
id: "0"
masterID: 0
name: Array[1]
nic: Array[1]
after JSON.STRINGIFY it becomes
"{"name":["nouman","nouman"],"nic":["9089898","9089898"],"designation": ["jkkhjk","jkkhjk"],"company":["uk","uk"],"cell":["+923012324265","+923012324265"],"address":["hkjhjk","hkjhjk"],"id":"0","MDate":"04-08-2015","MTime":"1010","MPurpose":1,"masterID":0,"RowNumber":3}"
their are 2 adresses , cell etc as array[]
my ajax method correct
$.ajax({
type: "POST",
url: "AddNewMeeting.aspx/SetFileName",
contentType: "application/json;charset=utf-8",
data: JSON.stringify(Meeting),
dataType: "json",
success: function (data) {
alert(data);
},
error: function (result) {
//alert("Error login");
}
});
}
my web method works only when i use parameters other then arrays like adress , cell etc
[WebMethod]
public static string SetFileName(string MDate, int MPurpose, string MTime, int RowNumber)
{
string c = "d";
return c;
}
i want to recieve
//string[] address, string[] cell, string[] company, string[] designation, int id, int masterID, string[] name, string[] nic)
also in parameter but how it would not work
We can send arrays as parameter like this
companyArray = ['Value1', 'Value2']
result = { MDate: "04-08-2015", companies: companyArray }
return JSON.stringify(result)
Where web service will be
public string webService(string MDate, string[] companies)
It works for me
You need to add the traditional property to your AJAX request, set it to true and remove the JSON.stringify:
var meetingData = {
MDate: "04-08-2015",
MPurpose: 1,
MTime: "1010",
RowNumber: 2,
address: [ 'string1', 'string2' ],
cell: [ 'string1', 'string2' ],
company: [ 'string1', 'string2' ],
designation: [ 'string1', 'string2' ],
id: "0",
masterID: 0,
name: [ 'string1', 'string2' ],
nic: [ 'string1', 'string2' ],
};
$.ajax({
type: "POST",
url: "AddNewMeeting.aspx/SetFileName",
contentType: "application/json;charset=utf-8",
data: meetingData,
dataType: "json",
traditional: true,
success: function (data) {
alert(data);
},
error: function (result) {
alert("Error login");
}
});
Related
Not getting array of data from ajax to controller.
$.ajax({
type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: {
"Query": JSON.stringify(Query) //change this
success: function() {}
});,
And array of Query :
0: {label: "abc:", value: "123", type: "Select"} 1: {label: "xyz",
value: "Hum", type: "text"}
Can anyone help ?
Try something like this
<script type="text/javascript">
var query=[{label: "abc:", value: "123", type: "Select"},{label: "abc:", value: "1232", type: "Select"} ];
$.ajax({ type: "POST",
url: "/Home/List",
traditional: true,
contentType: 'application/json',
data: JSON.stringify(query),
success: function (){
} });
</script>
I think something along this may work for you.
function sendarray() {
var arr = [];
var json = {
"label": 'abc',
"value": 1234,
"Name": 'Name'
};
arr.push(json);
json = {
"label": 'abc2',
"value": 1234,
"Name": 'Name2'
};
arr.push(json);
var myarray = JSON.stringify(arr);
$.ajax({
url: '/controller/GetArray',
type: 'POST',
data: { array: myarray },
success: function (data) {
//Do something
},
error: function () {
//Do something
}
});
}
then in the controller
public JsonResult GetArray(string array)
{
var obj = JsonConvert.DeserializeObject<object>(array);
return Json("");
}
This will send an string with all the data in the array to the controller, then you turn string with json format into an object list
I am working with the Twitter API for trends (see: https://developer.twitter.com/en/docs/trends/trends-for-location/api-reference/get-trends-place).
The API returns the following JSON:
{
trends: [
{
name: 'Boris',
url: 'http://twitter.com/search?q=Boris',
promoted_content: null,
query: 'Boris',
tweet_volume: 1083274
},
{
name: '#COVID19',
url: 'http://twitter.com/search?q=%23COVID19',
promoted_content: null,
query: '%23COVID19',
tweet_volume: 2088454
},
{
name: '#WorldHealthDay',
url: 'http://twitter.com/search?q=%23WorldHealthDay',
promoted_content: null,
query: '%23WorldHealthDay',
tweet_volume: 250817
}
],
as_of: '2020-04-07T14:06:49Z',
created_at: '2020-04-07T14:03:32Z',
locations: [ { name: 'London', woeid: 44418 } ]
}
I would like to transform this into a Javascript array containing all of the values where the key is name; ie.:
arr=["Boris", "#COVID19", "WorldHealthDay"]
How can I achieve this? From what I have read, native JavaScript JSON parsers cannot handle duplicate keys.
your data:
trends = [
{
name: 'Boris',
url: 'http://twitter.com/search?q=Boris',
promoted_content: null,
query: 'Boris',
tweet_volume: 1083274
},
{
name: '#COVID19',
url: 'http://twitter.com/search?q=%23COVID19',
promoted_content: null,
query: '%23COVID19',
tweet_volume: 2088454
},
{
name: '#WorldHealthDay',
url: 'http://twitter.com/search?q=%23WorldHealthDay',
promoted_content: null,
query: '%23WorldHealthDay',
tweet_volume: 250817
}
];
then use map
var ans = trends.map(d => d.name)
results:
ans = ["Boris", "#COVID19", "#WorldHealthDay"]
Arrays can contain duplicate VALUES, which is what you've requested. Arrays do not contain keys, and these strings in the array are also values of the 'name' key inside of the JSON returned from the twitter API.
To solve your problem, for example, with a very basic iteration and no Array.map
const data = JSON.parse(data_str);
const arr = [];
for (const trend of data.trends) {
arr.push(trend.name);
}
I have 2 objects generated by sqlite execution:
var info_update = {
id: 270,
cancelados: 2,
concluidos: 2,
total: 914
}
var participantes = [
{id: "10",
nome: "Antonio",
idade: "4",
ativo: 1,
msg: "Backorder"
},
{id: "11",
nome: "Carlos",
idade: "1",
ativo: 1,
msg: "Flagged"
}
]
For send the object I use this method on service:
var headers = {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
};
return $http({
method: "POST",
url: "remote_url.com/action",
data: {info_update: info_update, participantes: participantes},
headers : headers
})
What's the problem?
The parameter info_update it's sent to server, but the parameter participantes it's send empty, as appears in the attached image
I need send ALL data for serve.
How i do it?
Your participantes is not object its array try changing it to object using .map function
I try to send an array of json objects to server:
var objectData = [
{ Description: "Bezeichnung", Value: "1", Name: "Betrag (Brutto)" },
{ Description: "Dies ist die erste Bezeicnung", Value: "101", Name: "11,90" },
{ Description: "Dies ist die zweite Bezeicnung", Value: "12", Name: "11,90" }
];
$.ajax({
url: "/system/createinvoice",
data: JSON.stringify({ pos: objectData }) ,
dataType: 'json',
type: 'POST',
});
C#
public class InvoicePos
{
public string Description { get; set; }
public Nullable<double> Value { get; set; }
public string Name { get; set; }
}
[POST("/system/createinvoice")]
public void newquestion2(InvoicePos[] pos)
{
// pos is always null
}
The dataType property is saying what you expect back from the server. Try setting the contentType:
contentType: 'application/json'
Try
data: JSON.stringify({ pos: #objectData })
Also, check what is being rendered in the View through the browser. The reason you are getting null is likely because JavaScript is not getting a proper value.
function SendArrayOfObjects()
{
var things = [{ id: 1, color: 'red' }, { id: 2, color: 'blue' }, { id: 3, color: 'yellow' }];
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/MyServices.aspx/GetData")%>",
data: JSON.stringify({ objdata: things }),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function()
{
$("#msg").html("data sent successfully!");
},
error: function()
{
$("#msg").html(" Can not send data!");
}
});
}
I have the following data as json:
"Table":[
{
"AF":2000.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":100.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":15000.00
"RegionNumber":2
"RegionName":"Istanbul"
},
{
"AF":31000.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":11000.00
"RegionNumber":2
"RegionName":"Istanbul"
}
]
I want to arrange the data in the following format in Javascript.
series: [{
name: 'Black Sea',
data: [2000, 100, 31000],
stack: 'Bookings'
}, {
name: 'Istanbul',
data: [15000,11000,0],
stack: 'Bookings'
}]
How can I accomplish this transformation?
This almost does what you ask and uses Ramda.js too
const data = {
Table: [
{
AF: 2000,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 100,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 15000,
RegionName: "Istanbul",
RegionNumber: 2
},
{
AF: 31000,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 11000,
RegionName: "Istanbul",
RegionNumber: 2
}
]
}
const transfromTableData =
R.pipe(
R.groupBy(R.prop("RegionName")),
R.map(R.pluck("AF")),
R.toPairs,
R.map(R.zipObj(["name", "data"]))
)
const transfromData = (data) => ({
series: transfromTableData(data.Table)
})
console.log(transfromData(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
In pure JavaScript:
var memo = {}
for (var i in table) {
var item = table[i];
if (memo[item.RegionName] !== undefined) memo[item.RegionName].data.push(item.AF);
else memo[item.RegionName] = {
name: item.RegionName,
data: [item.AF],
stack: 'Bookings'
}
}
var result = {
series: []
};
for (var i in memo) {
result.series.push(memo[i]);
}
console.log(result);
I'm passing arrays of custom objects into List in web methods and it works just fine.
I'm, guessing that you're having a small JSON formatting issue because of the quotes around the property names. Try changing your object to this :
var scoresList = [{TraitID:1, TraitScore:2}, {TraitID:2, TraitScore:5}];
and change your data line to this :
data: JSON.stringify({ scores : scoresList }),
Hope that helps...
UPDATE: working example...
<script type="text/javascript">
$(function () {
var scoresList = [{ TraitID: 1, TraitScore: 2 }, { TraitID: 2, TraitScore: 5}];
$.ajax({ type: "POST",
url: "Tryouts.aspx/Test",
data: JSON.stringify({ scores: scoresList }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d == true) {
alert("success!!!!!");
} else {
alert("problem!!!!!!!!!");
}
},
error: function (xhr) {
alert("ERROR");
}
});
});
</script>
Here's the codebehind :
public class Score
{ // default constructor
public Score() { }
public int TraitID { get; set; }
public double TraitScore { get; set; }
}
[WebMethod]
public static bool Test( List<Score> scores )
{
return true;
}