Pass Array of Array to Server Jquery Ajax - javascript

When I try passing array of array to server it gives(on server log)
1 => [object, object], 2=> [object, object]
using ajax data: data
data on console.log shows:
[Object {name="abc", place="us"}, Object {name="pqr", place="jp"}]
actual array is as follow:
data.push({name: "abc", place: "us"})
data.push({name: "pqr", place: "jp"})
I would like output as (on server):
Person1 = {name="abc", place="us"}
Person2 = {name="pqr", place="jp"}
I tried jQuery.Serialize it does not work and trying to convert it JSON but failed on client side.(giving output [ ])
I am not sure, where I am going wrong. Can I directly send data array to server?
Thanks
Viral

JavaScript arrays and objects are not the same thing. Arrays have elements with numeric indexes, while objects have properties with string key names.
You probably want something like this:
var data = {
Person1 : {name:"abc", place:"us"},
Person2 : {name:"pqr", place:"jp"}
};
This creates an object (data) which has properties "Person1" and "Person2" that are themselves references to objects with "name" and "place" properties.
Or, the equivalent of the array push method to add your properties to the object is to do this:
// create an empty object
var data = {};
// set properties
data["Person1"] = {name:"abc", place:"us"};
data["Person2"] = {name:"pqr", place:"jp"};
// or use dot notation:
data.Person3 = {name:"xyz", place:"au"};

here is an ajax if you like to try, serializing and passing data object as JSON to the server side.
var data = {
Person1 : { name:'abc', place:'us'},
Person2 : { name:'pqr', place:'jp'}
}
$.ajax({
type: 'POST',
url: 'url',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(msg) {
//success
}
});

Related

Can not get value from JSON object

I'm having trouble getting the data value from JSON object. Here is my code:
var ab_id = $( "#ab_id" ).val();
$.ajax({
type: 'GET',
contentType: 'application/json',
url: 'edit_account.php',
data: {ab_id:ab_id, u_id:u_id},
success: function(data)
{
alert(data.ab_name);
},
});
When I do alert(data), I got the actual data like this:
{
"ab_id":"7",
"ab_name":"Lily's Storage Address",
"ab_ship_name":"LIly C\/O SELF STORAGE",
"ab_addr_1":"C\/O Lily",
"ab_addr_2":"16 PIUMA AVENUE, UNIT #2",
"ab_city":"CERI",
"ab_state":"CA",
"ab_postal":"90700",
"ab_phone":null,
"ab_default":"0",
"ab_is_storage":"1"
}
However, when I retrieve the data value by using data.ab_name, it returns undefined.
Am I missing something here?
Use bracket notation
alert(data['ab_name']);
for reference https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors
Parse your string to a object
data = JSON.parse(data);
alert(data.ab_name);

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?

I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?
My specific situation: I have an array defined as shown below:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...
and I need to turn this into a string to pass to $.ajax() like this:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: "{'countries':['ga','cd']}",
...
You can use JSON.stringify(countries);
var c = {
countries: countries
}
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: JSON.stringify(c),
contentType: "application/json"
...
Note that you will want to specify contentType; otherwise, URI-encoding is assumed.
You can use JSON.stringify() to turn any object in to a JSON string:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
var json = JSON.stringify({ countries: countries}); // = '{"countries":["ga","cd"]}'
// or more simply:
var countries = [ 'ga', 'cd' ];
var json = JSON.stringify({ countries: countries}); // = '{"countries":["ga","cd"]}'
However, you should note that it's better practice to provide the data property of $.ajax with an object as jQuery will then create the JSON for you and at the same time escape any invalid characters and do any required encoding. Try this:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: {
'countries': countries
}
});
you can use JSON.parse() to convert object to json
like this
countries = JSON.parse(countries);
object is convert in json and store in countries variable

.serialize() an array of variables in Javascript

I have a list of variables available to me and I want to send it via $.ajax post. What format would I have to keep these in to use the function .serialize? I keep getting this error:
Object 'blank' has no method 'serialize'
I've tried to make them an array and I've tried jQuery.param(). I have a feeling this is simple but I can't seem to get it. Thanks!
var $data = jQuery.makeArray(attachmentId = attachmentID, action = 'rename', oldName = filename, newName, bucketName, oldFolderName, newFolderName, projectId = PID, businessId = BID);
var serializedData = $data.serializeArray();
//alert(theurl);
$.ajax({ type: "post", url: theurl, data: serializedData, dataType: 'json', success: reCreateTree });
.serialize is for form elements:
Encode a set of form elements as a string for submission.
The $.ajax documentation says for the data option:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
So all you need to do is passing an object. For example:
$.ajax({
type: "post",
url: theurl,
data: { // <-- just pass an object
attachmentId: attachmentID,
action: 'rename',
// ...
},
dataType: 'json',
success: reCreateTree
});
It seems you're used to the PHP style of array's (associated arrays). In Javascript, objects are basically the same thing (though can be MUCH more complicated).
So if you are trying to create an array like this in php it would be
$array = array(
"foo" => "bar",
"bar" => "foo",
);
in Javascript using an object instead of an array it would be
var arr = {
foo: "bar",
bar: "foo"
}

Javascript array converted to JSON objects instead of array

I am trying to submit some JSON to my web app and I want the JSON to be like this:
{
"thing1" :
{
"something" : "hello"
},
"list_of_things" :
[
{
"item1" : "hello"
},
{
"item2" : "hello"
}
]
}
Here I have one JSON object and a JSON array that holds JSON objects. When I create the data to submit in Javascript I do:
form = {
"thing1" : {
"something" : somethingVariable
},
"list_of_things" : listArray
}
Here 'listArray' is a Javascript Array object of Javascript hash objects. I submit this using jQuery's ajax method but instead of javascript array displaying as the JSON array desired it converts it to a series of JSON objects like this:
{ "1" : { "thing1" : "something" }, "2" : { "thing2" : "something" }...
How can I get the array to be submitted as an array rather than be converted into a series of JSON objects with the array indexes as keys?
EDIT#1: 'listArray' is a simple Javascript array that is defined like so:
var listArray = new Array();
listArray.push({ "thing1" : "something" });
listArray.push({ "thing2" : "something" });
EDIT#2: 'form' is sent to the server with the following call:
$.ajax({
type: 'POST',
url: '/url',
dataType: "json",
data: form,
success: function(data) {
/* success code here */
}
});
Have a look here. If you are truly trying to post JSON you will need to send the string, not an object literal. You could use JSON.stringify (or a more supported JSON solution) on form.
$.ajax({
url: "/url",,
dataType: "json",
type: "POST",
processData: false,
contentType: "application/json",
data: JSON.stringify(form)
});

How to convert variables into json?

I want to send json data to ajax but how do you convert variables into json or convert an array to json?
$(".confirm_order").click(function(event) {
event.preventDefault();
var street = $("#street").val();
var location = $("#location").val();
var number = $("#number").val();
var f = ???
$.ajax({
type: 'post',
url: "/orders",
dataType: "json",
data: f,
success: function (l) {
alert("Done");
}
});
});
If you really want to convert the data into JSON, you have to create an object or array and use JSON.stringify (available in newer browser and can be loaded form here):
var f = JSON.stringify({street: street, location: location, number: number});
but you cannot just set the data attribute to f then. You have to assign it to another variable:
data: {data: f}
This will produce the POST parameters like so:
data={"number":"value of number","location:...}
However, there is not reason to create JSON here. I would sent the values as normal post parameters. For that you just create an object like above and assign it to data:
data: {street: street, location: location, number: number}
This will create the POST parameters:
street=valueofstreet&location=valueoflocation&...
This would be easier as you don't have to parse the JSON at the server side.
If you want to send a JSON formatted request to the server you could specify the proper content type for this request and then use the JSON.stringify method:
var street = $('#street').val();
var location = $('#location').val();
var number = $('#number').val();
$.ajax({
type: 'post',
url: '/orders',
dataType: 'json',
data: JSON.stringify({ street: street, location: location, number: number }),
contentType: 'application/json; charset=utf-8',
success: function (l) {
alert("Done");
}
});
This will send the following in the POST body:
{ street: 'foo', location: 'bar', number: 'baz' }
Obviously the server side script you are sending this AJAX to need to be capable of handling and parsing JSON strings.
var f = {}
f['street'] = $("#street").val();
f['location'] = $("#location").val();
f['number'] = $("#number").val();
var f = {
"street": street,
"location": location,
"number": number
};
Use JSON.stringify from json2.js
Don't forget to specify contentType: 'application/json' in your config object.
try this. values will be replaced respectively
{street : street,location : location, number : number}

Categories

Resources