Passing array to ajax - javascript

How I can pass a list or array to ajax?
var intArray = [];
$.ajax({
url: '/User/GetGroup',
type: 'GET',
data: intArray,
traditional: true,
success: function (result) {
$(result).each(function () {
var id = this.Id;
var nome = this.Nome;
$("#Default").append($('<option></option>').val(id).html(nome));
});
}
});
Like this way, still doesn't work.
Thanks!

You can pass the array like that, or use data: JSON.stringify(intArray). In ASP.NET MVC, we use the JSON 2 javascript library, available in a Nuget package.
success: function (serverResult) {
// create an object array from json string.
var results = JSON.parse(serverResult);
for ( var item in results){
$("#Default").append($('<option></option>').val(item.Id).html(item.Nome));
}
}

I used data: { i: intArray }, and works too!

Related

array is empty even if it was successfully mapped

I'm running into issues with _.map (using underscore.jshttp://underscorejs.org).
getCalories: function() {
var encode = "1%20";
var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#";
_.map(ingArray, function(elem)
{
return $.ajax(calSource, {
dataType: "json",
jsonp: "jsonp",
data: "ingr=" + encode + elem,
complete: function(r) {
var obj = JSON.parse(r.responseText);
var calorie = obj.calories;
calArray.push(calorie);
console.log(calArray);
}
});
});
},
I need to use the latest iteration of calArray in another function. However, it always comes up as undefined. So I inserted a console.log above and this is what I get:
app.js:177 is the console.log
Is this a scoping issue? Also, if it's logging prior to the push then I can see why it's coming up as undefined. How do I get around it?
I believe underscore's map produces a new array, in your case the new array will contain a bunch promises (ajax-requests)
You may want to assign this to a variable first, something like below:
getCalories: function () {
var encode = "1%20";
var calSource = "https://api.edamam.com/api/nutrition-data?app_id=#&app_key=#";
var requests = _.map(ingArray, function(elem) {
return $.ajax(calSource, {
dataType: "json",
jsonp: "jsonp",
data: "ingr=" + encode + elem
});
});
$.when.apply($, requests).then(function(results) {
console.log(results); // can you take a screenshot of this output
var calories = _.map(results, function(result) {
return JSON.parse(result.responseText).calories;
});
calArray = calArray.concat(calories);
});
}

Delete key/value pair from json array obtained from ajax response if key is found

I am fetching data from one list in sharepoint and storing it in json array to pass it onto another function to create a new item in Sharepoint list.The first function is:
$.ajax({
url: someSharepointListUrl,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var array = new Array();
for (var i=0; i< data.d.results.length; i++) {
var it=data.d.results[i];
array.push({
AllLinks: it.AllLinks,
LinkURL: it.LinkURL.Url
});
}
dataCharts=JSON.stringify(array);
alert(dataCharts);
AddDefaultLinks(dataCharts);
},
error: function (data) {
alert(data.responseJSON.error);
}
});
The item is stored in the list as as:[{"Name":"Name1","URL":"http://www.name1.com"},{"Name":"Name2","URL":"http://www.name2.com"}]
The second function which fetches data from list after item is created is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var c = [];
var stringData = JSON.stringify(data.d.results[0].AllLinks);
//alert(stringData);
c.push(JSON.parse(stringData));
alert(c);
var xonly = c.filter(function (entry){
return entry.AllLinks != x;
});
alert(xonly);
},
error: function() {
alert('fail');
}
});
I need to match if a value exists in this newly created list Item.If yes then delete it eg Lin.
value of c(json array) here is:[{"Name":"Name1","URL":"http://www.name1.com"},{"Name":"Name2","URL":"http://www.name2.com"}]
`
entry.AllLinks doesnt filter data here.AllLinks is undefined in entry.AllLinks.Please help
Use Array.findIndex() to find the desired value inside array, and use Array.splice() method to remove that object.

javascript, array of string as JSON

I'm having problems with passing two arrays of strings as arguments in JSON format to invoke ASMX Web Service method via jQuery's "POST".
My Web Method is:
[ScriptMethod(ResponseFormat=ResponseFormat.Json)]
public List<string> CreateCollection(string[] names, string[] lastnames)
{
this.collection = new List<string>();
for (int i = 0; i < names.Length; i++)
{
this.collection.Add(names[i] + " " + lastnames[i]);
}
return this.collection;
}
Now, the js:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: dataS,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
GetJSONData() is my helper method creating two arrays from column in a table. Here's the code:
function GetJSONData() {
//take names
var firstnames = $('#data_table td:nth-child(1)').map(function () {
return $(this).text();
}).get(); //["One","Two","Three"]
//take surnames
var surnames = $('#data_table td:nth-child(2)').map(function () {
return $(this).text();
}).get(); //["Surname1","Surname2","Surname3"]
//create JSON data
var dataToSend = {
names: JSON.stringify(firstnames),
lastnames: JSON.stringify(surnames)
};
return dataToSend;
}
Now, when I try to execude the code by clicking button that invokes CreateArray() I get the error:
ExceptionType: "System.ArgumentException" Message: "Incorrect first
JSON element: names."
I don't know, why is it incorrect? I've ready many posts about it and I don't know why it doesn't work, what's wrong with that dataS?
EDIT:
Here's dataToSend from debugger for
var dataToSend = {
names: firstnames,
lastnames: surnames,
};
as it's been suggested for me to do.
EDIT2:
There's something with those "" and '' as #Vijay Dev mentioned, because when I've tried to pass data as data: "{names:['Jan','Arek'],lastnames:['Karol','Basia']}", it worked.
So, stringify() is not the best choice here, is there any other method that could help me to do it fast?
Try sending like this:
function CreateArray() {
var dataS = GetJSONData(); //data in JSON format (I believe)
$.ajax({
type: "POST",
url: "http://localhost:45250/ServiceJava.asmx/CreateCollection",
data: {names: dataS.firstnames,lastnames: dataS.surnames} ,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
//something
}
})
}
This should work..
I think since you are already JSON.stringifying values for dataToSend property, jQuery might be trying to sending it as serialize data. Trying removing JSON.stringify from here:
//create JSON data
var dataToSend = {
names : firstnames,
lastnames : surnames
};
jQuery will stringify the data when this is set dataType: "json".
Good luck, have fun!
Altough, none of the answer was correct, it led me to find the correct way to do this. To make it work, I've made the following change:
//create JSON data
var dataToSend = JSON.stringify({ "names": firstnames, "lastnames": surnames });
So this is the idea proposed by #Oluwafemi, yet he suggested making Users class. Unfortunately, after that, the app wouldn't work in a way it was presented. So I guess if I wanted to pass a custom object I would need to pass it in a different way.
EDIT:
I haven't tried it yet, but I think that if I wanted to pass a custom object like this suggested by #Oluwafemi, I would need to write in a script:
var user1 = {
name: "One",
lastname:"OneOne"
}
and later pass the data as:
data = JSON.stringify({ user: user1 });
and for an array of custom object, by analogy:
data = JSON.stringify({ user: [user1, user2] });
I'll check that one later when I will have an opportunity to.

I want to store the data in an array from the web api

I want to use values from the web api , everything is running fine but when I read values from the url in a single variable it comes as large data:
var orguni = "http://hospdev.hispindia.org/haryana_220/api/organisationUnits?fields=name,id,code";
$.ajax({
type: "GET",
url: orguni,
dataType: "xml",
crossDomain: true,
headers: {
},
success: function (xml) {
$(xml).find('organisationUnit ').each(function () {
var ou = $(this).attr('id');
console.log("UID: "+ ou);
});
}
});
Now when I display ou it returns a list of different id's and I want to use all id's as separate value, can anybody tell me how to do that.
Currently it returns:
index.html:26 UID: g8cMOWx5ydN
index.html:26 UID: Q2FEgPgHvMr
index.html:26 UID: XpIf2v7cJRX
index.html:26 UID: uoPA7guOuLa
index.html:26 UID: BLpdsMuZcqD
When I use console.log(ou[0]); it returns 1st char from each like:
g
Q
x
...
var array = [];
$(xml).find('organisationUnit ').each(function () {
var ou = $(this).attr('id');
array.push(ou);
});
array[0] will now be g8cMOWx5ydN.
What ou[0] is doing is turning g8cMOWx5ydN into an array and returning index 0, which is 'g'.
Edit Following Comment
you can either use the Id as you retrieve it, and not use the array.
$(xml).find('organisationUnit ').each(function () {
var id = $(this).attr('id');
// use id ajax call here
});
or you can use the array after the each
var array = [];
$(xml).find('organisationUnit ').each(function () {
var ou = $(this).attr('id');
array.push(ou);
});
//other code
for(var i=0; i<array.length; i++){
var id = array[i];
// use id ajax call here
}

Posting multiple objects in an ajax call

I have a list of data which is within multiple objects.
Each object has an ID and a status and then the main object has a type and a form id.
The problem I am having is posting result via ajax as it doesn't like the multiple objects.
This is the code I have:
var permissionsData = [];
$(".workflowBox").each(function(index, element) {
var obj = {
status: $(this).attr("data-user-status"),
record:$(this).attr("data-user-id")
};
permissionsData.push(obj);
});
permissionsData.userGroupID = userGroupID;
permissionsData.formID = formID;
var posting = $.ajax({
url: "http://www.test.com",
method: 'post',
data: permissionsData
});
How can I wrap/send permission data?
How about changing your array to an object and using jQuery's param function.
var permissionsData = {};
$(".workflowBox").each(function(index, element) {
var obj = {
status: $(this).attr("data-user-status"),
record:$(this).attr("data-user-id")
};
permissionsData[index] = obj;
});
permissionsData.userGroupID = userGroupID;
permissionsData.formID = formID;
var posting = $.ajax({
url: "http://www.test.com",
method: 'post',
data: $.param(permissionsData)
});
maybe you can use json2.js
it can parse the object to json string and parse the json string to object
you can use JSON.stringify method for parse object to json string

Categories

Resources