Posting multiple objects in an ajax call - javascript

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

Related

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.

Pass Json Object and String Value at once in Ajax

I want to pass a Json Object and String Value together in ajax call. I have attached my code below.
$('#ddcountryid').change(function () {
var jdata = ko.mapping.toJSON(viewModel);
var Cid = $(this).val();
//alert(intCountry);
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")',
type: 'POST',
data: jdata,
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.redirect) {
location.href = resolveUrl(data.url);
}
else {
ko.mapping.fromJS(data, viewModel);
}
},
error: function (error) {
alert("There was an error posting the data to the server: " + error.responseText);
},
});
});
My Action Method
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I am getting wrapper object with Values, but how can get the CID as well. Can anyone please help me on this??.
you can pass it as query string parameter:
var Cid = $(this).val();
$.ajax({
url: '#Url.Action("PopulateDropDown", "Pepmytrip")' + '?cID=' + Cid,
...
server side:
public JsonResult PopulateDropDown(Wrapper wrapper, string cID)
{
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
OR add a new property to your Wrapper object as Gavin Fang suggested:
var Cid = $(this).val();
viewModel.Cid = Cid;
var jdata = ko.mapping.toJSON(viewModel);
server side code:
public JsonResult PopulateDropDown(Wrapper wrapper)
{
var cid = wrapper.Cid;
wrapper.Destinations = new SelectList(context.Destinations.Where(c=>c.CountryId == cID), "id", "Name").ToList();
return Json(wrapper);
}
I think you can add a property to store you 'CID' to your viewModel.
and you can get the CID in the 'success' function in javascript in here, I think.
You can achieve this is two ways:
You can add extra field for existing json 'jdata' by defining field jdata.cid = null; and assigning it as jdata.cid = $(this).val();.
Prepare an object to hold both json data and string value:
var obj = {"json": jdata, "string":$(this).value()};
then pass obj in data parameter

Passing array to ajax

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!

Passing string array from ASP.NET to JavaScript

I am trying to call the server side from JavaScript and then pass a string array back to JavaScript, but running into problems.
// Call the server-side to get the data.
$.ajax({"url" : "MyWebpage.aspx/GetData",
"type" : "post",
"data" : {"IdData" : IdData},
"dataType" : "json",
"success": function (data)
{
// Get the data.
var responseArray = JSON.parse(data.response);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
On the ASP.Net server side, I have:
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static object GetTip(String IdTip)
{
int iIdTip = -1;
String[] MyData = new String[2];
// Formulate the respnse.
MyData[0] = "My header";
MyData[1] = "My body";
// Create a JSON object to create the response in the format needed.
JavaScriptSerializer oJss = new JavaScriptSerializer();
// Create the JSON response.
String strResponse = oJss.Serialize(MyData);
return strResponse;
}
I am probably mixing things up, as I am still new to JSON.
UPDATE with error code:
Exception was thrown at line 2, column 10807 in http://localhost:49928/Scripts/js/jquery-1.7.2.min.js
0x800a03f6 - JavaScript runtime error: Invalid character
Stack trace:
parse JSON[jquery-1.7.2.min.js] Line 2
What is my problem?
I modified your ajax call script to :
// Call the server-side to get the data.
$.ajax({
url: "WebForm4.aspx/GetTip",
type: "post",
data: JSON.stringify({ IdTip: "0" }),
dataType: "json",
contentType: 'application/json',
success: function (data) {
// Get the data.
var responseArray = JSON.parse(data.d);
// Extract the header and body components.
var strHeader = responseArray[0];
var strBody = responseArray[1];
// Set the data on the form.
document.getElementById("divHeader").innerHTML = strHeader;
document.getElementById("divBody").innerHTML = strBody;
}
});
Note that I added contentType: 'application/json' and changed
var responseArray = JSON.parse(data.response);
to
var responseArray = JSON.parse(data.d);
This s purely out of guess work. But see if this is what you are getting:-
In your Ajax call, your data type is json and looking at the method you are returning a json string. So you do not need to do JSON.parse(data.response). Instead just see if the below works for you. Also i dont see a response object in your Json, instead it is just an array. So it must be trying to parse undefined
var strHeader = data[0];
var strBody = data[1];

jQuery post() with serialize and extra data

I'm trying to find out if it's possible to post serialize() and other data that's outside the form.
Here's what I thought would work, but it only sends 'wordlist' and not the form data.
$.post("page.php",( $('#myForm').serialize(), { 'wordlist': wordlist }));
Does anyone have any ideas?
You can use serializeArray [docs] and add the additional data:
var data = $('#myForm').serializeArray();
data.push({name: 'wordlist', value: wordlist});
$.post("page.php", data);
Try $.param
$.post("page.php",( $('#myForm').serialize()+'&'+$.param({ 'wordlist': wordlist })));
An alternative solution, in case you are needing to do this on an ajax file upload:
var data = new FormData( $('#form')[0] ).append( 'name' , value );
OR even simpler.
$('form').on('submit',function(e){
e.preventDefault();
var data = new FormData( this ).append('name', value );
// ... your ajax code here ...
return false;
});
When you want to add a javascript object to the form data, you can use the following code
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeArray();
for (var key in data) {
if (data.hasOwnProperty(key)) {
postData.push({name:key, value:data[key]});
}
}
$.post(url, postData, function(){});
Or if you add the method serializeObject(), you can do the following
var data = {name1: 'value1', name2: 'value2'};
var postData = $('#my-form').serializeObject();
$.extend(postData, data);
$.post(url, postData, function(){});
In new version of jquery, could done it via following steps:
get param array via serializeArray()
call push() or similar methods to add additional params to the array,
call $.param(arr) to get serialized string, which could be used as jquery ajax's data param.
Example code:
var paramArr = $("#loginForm").serializeArray();
paramArr.push( {name:'size', value:7} );
$.post("rest/account/login", $.param(paramArr), function(result) {
// ...
}
$.ajax({
type: 'POST',
url: 'test.php',
data:$("#Test-form").serialize(),
dataType:'json',
beforeSend:function(xhr, settings){
settings.data += '&moreinfo=MoreData';
},
success:function(data){
// json response
},
error: function(data) {
// if error occured
}
});
You can use this
var data = $("#myForm").serialize();
data += '&moreinfo='+JSON.stringify(wordlist);
You could have the form contain the additional data as hidden fields which you would set right before sending the AJAX request to the corresponding values.
Another possibility consists into using this little gem to serialize your form into a javascript object (instead of string) and add the missing data:
var data = $('#myForm').serializeObject();
// now add some additional stuff
data['wordlist'] = wordlist;
$.post('/page.php', data);
I like to keep objects as objects and not do any crazy type-shifting. Here's my way
var post_vars = $('#my-form').serializeArray();
$.ajax({
url: '//site.com/script.php',
method: 'POST',
data: post_vars,
complete: function() {
$.ajax({
url: '//site.com/script2.php',
method: 'POST',
data: post_vars.concat({
name: 'EXTRA_VAR',
value: 'WOW THIS WORKS!'
})
});
}
});
if you can't see from above I used the .concat function and passed in an object with the post variable as 'name' and the value as 'value'!
Hope this helps.

Categories

Resources