Append an object to an array's value? - javascript

What I'm trying to accomplish in php is the following:
$var->doSomething(['chris' => ['age' => 22], 'evan']);
I'm sending an array via a formData (not like the above question, obviously), and php reads the array perfectly like this:
$array = $_POST('arrayOfValues');
$var->doSomething($array);
The data on my js formdata is the following:
var array = ['chris', 'evan'];
var data = new FormData();
array.forEach(function(item){
data.append('arrayOfValues[]', item);
});
I have no idea how to accomplish it, an acquaintance told me to try an object, but it didn't work (I dunno if I have to parse it somehow in php or js).
PD: JQuery or JS are accepted, but I'd prefer the latter for learning purposes

The formData creates only a set of key/values pairs representing form fields.
If you want to send complex objects to PHP you have to use JSON.
To create JSon objects use:
var myArrayObj = { ... };
var json = JSON.stringify( myArrayObject);
More information on json: http://www.json.org/js.html
So, in PHP, use:
var_dump(json_decode($json)); //where $json is your data from JS

Related

access javascript object in servlet [duplicate]

I am creating and sending a JSON Object with jQuery, but I cannot figure out how to parse it properly in my Ajax servlet using the org.json.simple library.
My jQuery code is as follows :
var JSONRooms = {"rooms":[]};
$('div#rooms span.group-item').each(function(index) {
var $substr = $(this).text().split('(');
var $name = $substr[0];
var $capacity = $substr[1].split(')')[0];
JSONRooms.rooms.push({"name":$name,"capacity":$capacity});
});
$.ajax({
type: "POST",
url: "ParseSecondWizardAsync",
data: JSONRooms,
success: function() {
alert("entered success function");
window.location = "ctt-wizard-3.jsp";
}
});
In the servlet, when I use request.getParameterNames() and print it out to my console I get as parameter names rooms[0][key] etcetera, but I cannot parse the JSON Array rooms in any way. I have tried parsing the object returned by request.getParameter("rooms") or the .getParameterValues("rooms") variant, but they both return a null value.
Is there something wrong with the way I'm formatting the JSON data in jQuery or is there a way to parse the JSON in the servlet that I'm missing?
Ask for more code, even though the servlet is still pretty much empty since I cannot figure out how to parse the data.
The data argument of $.ajax() takes a JS object representing the request parameter map. So any JS object which you feed to it will be converted to request parameters. Since you're passing the JS object plain vanilla to it, it's treated as a request parameter map. You need to access the individual parameters by exactly their request parameter name representation instead.
String name1 = request.getParameter("rooms[0][name]");
String capacity1 = request.getParameter("rooms[0][capacity]");
String name2 = request.getParameter("rooms[1][name]");
String capacity2 = request.getParameter("rooms[1][capacity]");
// ...
You can find them all by HttpServletRequest#getParameterMap() method:
Map<String, String[]> params = request.getParameterMap();
// ...
You can even dynamically collect all params as follows:
for (int i = 0; i < Integer.MAX_VALUE; i++) {
String name = request.getParameter("rooms[" + i + "][name]");
if (name == null) break;
String capacity = request.getParameter("rooms[" + i + "][capacity]");
// ...
}
If your intent is to pass it as a real JSON object so that you can use a JSON parser to break it further down into properties, then you have to convert it to a String before sending using JS/jQuery and specify the data argument as follows:
data: { "rooms": roomsAsString }
This way it's available as a JSON string by request.getParameter("rooms") which you can in turn parse using an arbitrary JSON API.
Unrelated to the concrete problem, don't use $ variable prefix in jQuery for non-jQuery objects. This makes your code more confusing to JS/jQuery experts. Use it only for real jQuery objects, not for plain vanilla strings or primitives.
var $foo = "foo"; // Don't do that. Use var foo instead.
var $foo = $("someselector"); // Okay.

Passing an array from javascript to ruby with sinatra

What I want to accomplish is to pass a 2D array from javascript to something that ruby will recognize. All objects are strings
I have been using gon-sinatra, but it doesn't do exactly what I need.
I can pass store the string I want to pass as gon.text doing
#temp = gon.text
array.push(#temp)
This doesn't work because it shows gon.text as a nil object type, when I want it as a string. gon.text.to_s returns an empty string, so when I try to display it, nothing happens. alert("<%= #temp %>") // displays an empty string
I'm at a bit of a loss here and don't know the best way to approach this. Would it be better to store the array as a json, and then read in the json using ruby instead?
Yes. Convert your array to json(a string) with js:
var data = JSON.stringify(yourArray);
Send the string to your ruby script. Then parse the string into an Array with ruby:
require 'json'
arr = JSON.parse(the_string)
In Javascript you do something like the following:
var myArray = [ ['str1','str2'], ['str3','str4'] ];
$.get('/endpoint', { myArray: myArray })
And your endpoint with sinatra would be:
get 'endpoint' do
myArrayStr = params[:myArray]
error!('invalid array') unless myArrayStr
#myArray = JSON.parse(myArrayStr)
gon.rabl 'goners/yourFile.rabl', :instance => self
end
And in your gon file you would reference this with:
alert(gon.myArray[0][0]); // str1

Json associative array accessing in jQuery

I am getting response in below format for every product and in a single call there can be many products. I am trying to access this data via jQuery but I'm not able to access it.
Productdata['someid'] = { "Product Json data"}
I am using below syntax in jQuery but not getting the data. Please suggest.
alert(Productdata['someid']);
Its not going as JSON format .
JSON is a key : value pair format ;
so your Productdata should be in below format:
Productdata = { 'someid' : "Product Json data"}
A Json like this
var data={"name":"somebody"};
To call
return data.name
Or
return data["name"]
The problem here is that JavaScript does not support associative arrays (scroll down to "Associative arrays, no way!"). It has some internal workarounds which make it appear as if it does, but really all it does is just adding the keys as properties.
So you would most likely be able to access it using Productdata.someid = ....
EDIT:
So assuming you have the following JSON string: {"id":"123"} (which is valid JSON), you can use it like this:
var jsonString = '{"id":"123"}';
var parsedJSON = $.parseJSON(jsonString);
var productID = "product_" + parsedJSON.id;
Does this help?
Some useful links: JSON format checker to make sure the JSON is valid.
Unfortunately I wasn't allowed to add more than 2 links, so the jQuery parseJSON function link is still in the comment below.

javascript array mistake

I used to create an array in js
var data = new Array();
data['id'] = self.iframeFields.id.val();
data['name'] = self.iframeFields.name.val();
data['location'] = self.iframeFields.location.val();
data['about'] = self.iframeFields.about.val();
data['company'] = self.iframeFields.company.val();
data['website'] = self.iframeFields.website.val();
but passing var data returns null value
but data['id'] return value.
What did I do wrong?
EDIT:
After nrabinowitz's answer, i was using
if ($.isArray( data )){
ajax({
url: myurl,
data: {
method: "updateProfile",
data: data
},
normalizeJSON: true,
success: function( response ){
// Check to see if the request was successful.
if (response.success){
alert(response);
} else if (onError){
// The call was not successful - call the error function.
alert(response);
}
}
});
}
as it is an object not an array,
it was not returning nothing,
Removing
if ($.isArray( data )){
}
solves the issue.
In Javascript, you want an object, not an array:
var data = {};
data['id'] = self.iframeFields.id.val();
// etc...
You're expecting the array to work like an associative array in PHP, but Javascript arrays don't work that way. I'm assuming you're setting these values by key, and then trying to iterate through the array with something like a for loop - but while you can set values by key, because in Javascript an array is just another object, these values won't be available in standard array iteration, and the length of the array will still be 0.
EDIT: You note that you're using jQuery's .ajax() function to post the data to the server. The .ajax() method expects an object containing key/value pairs, and sends them to the server as a GET or POST parameters. So in your case, if you're using an object as I describe above, your server will receive the parameters "id", "name", etc in the $_POST array - not a "data" parameter.
I suspect, though I haven't tested this, that using var data = new Array(); wouldn't work at all, because of the way jQuery serializes the data passed to .ajax() - even though an array is also an object, jQuery checks if it's an array and treats it differently:
If the object passed is in an Array, it must be an array of objects in the format returned by .serializeArray()
[{name:"first",value:"Rick"},
{name:"last",value:"Astley"},
{name:"job",value:"Rock Star"}]
So it wouldn't use the key/value pairs you set at all - you would be passing an empty array and no parameters would be passed to the server.
So the right approach here:
Use var data = {};
On the server, look for $_POST['id'], $_POST['name'], etc.
You're using the array like a regular object. You're augmenting the array with additional properties, but the array itself is still empty (you should have an array.length === 0, hence the null). Try changing
var data = new Array();
to
var data = {};
and see what you get.

Deleting particular data from a json object using JavaScript

I am using titanium for developing Android application. I want to delete some data from json object. My json object given below:
{"feeds":
[
{"username":"abc","user":"abc","feed":{"description":"dss","id":660,"user_id":1}},
{"username":"bcd","user":"bcd","feed":{"description":"dddd","id":659,"user_id":1}}
]
}
for receiving json object I used following code
var json = this.responseText;
var json = JSON.parse(json);
json.feeds.splice(0,1);
alert(json.feeds[0]);
I want to delete particular data from json object like json.feeds[0] using JavaScript. I am able to access json.feeds[0] but not able to delete. Is there any way to delete that data from json object using JavaScript?
You are using splice to properly remove an element from a javascript array:
json.feeds.splice(0,1)
Using the code you've provided it will look like:
(function(){
var json = {
"feeds": [
{"username":"abc","user":"abc","feed":{"description":"dss","id":660,"user_id":1}},
{"username":"bcd","user":"bcd","feed":{"description":"dddd","id":659,"user_id":1}}
]
};
json.feeds.splice(0,1);
console.log(json.feeds); // just to check that "feeds" contains only a single element
})();
Parse the JSON into a JavaScript data structure
Use splice to remove the elements you don't want from the array
Serialise the JavaScript objects back into JSON

Categories

Resources