javascript array mistake - javascript

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.

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.

How do I access this javascript object?

{"profit_center" :
{"branches":
[
{"branch": {"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3310","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3311","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3312","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3313","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"0","site_survey":"1","branch_number":"3314","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}},
{"branch":{"work_order":"1","cutover":"1","site_survey":"1","branch_number":"3315","quote":"1","configuration":"1","purchase_order":"1","hardware_swap":"1"}}
],
"profit_center_name":"Alabama"}}
I tried accessing it in ajax through this,
data.profit_center //data here is the ajax variable e.g. function(data)
or through this data["profit_center"]
but no luck
How do I access this javascript object properly. ?
By the way that code above is from console.log(data)
EDIT:
Result from console.log(data.profit_center) and console.log(data["profit_center"]) is undefined
You can put your datain a variable like
var json = data
and you can access profit_center like
alert(json.profit_center);
alert(json.profit_center.profit_center_name); //Alabama
for(var i =0 ;i<json.profit_center.branches.length;i++){
alert(json.profit_center.branches[i]);
}
Okay I have found out why it is undefined, It is a json object so I need to parse it before i can access it like a javascript object.
var json = JSON.parse(data);
Then that's it.
First parse your data if you've not already done so.
You can access, for example, each branch_number like so:
var branches = data.profit_center.branches;
for (var i = 0, l = branches.length; i < l; i++) {
console.log(branches[i].branch.branch_number);
}
In summary, profit_center is an object and branches is an array of objects. Each element in the array contains a branch object that contains a number of keys. Loop over the branches array and for each element access the branch object inside using the key names to get the values.
The profit center name can be found by accessing the profit_center_name key on the profit_center object:
console.log(data.profit_center.profit_center_name); // Alabama
You could even use the new functional array methods to interrogate the data and pull out only those branches you need. Here I use filter to pull those objects where the purchase_order is equal to 2. Note that the numeric values in your JSON are strings, not integers.
var purchaseOrder2 = branches.filter(function (el) {
return el.branch.purchase_order === '2';
});
DEMO for the three examples

Every character in an array being recognized with ".hasOwnProperty(i)" in javascript as true with Google Apps Script

This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.

form key+value pairs jquery plugin

Is there a way I can access the array of data that the browser compiles on a form submit - before the actual GET/POST operation in js/jq?
$("form").submit(function(event){
event.preventDefault();
//give me the data array here
});
I'm finding myself increasingly using AJAX - I call event.preventDefault(), grab the name/value pairs of all the elements contained in $(this) (the form) and then push them to the server via $.post(). It's becoming a pain the neck to assemble the data array manually. It would be great if a plugin existed of sorts:
$data = $("form").gimmeData();
Does something like this exist that supports all the major HTML input elements? Am I approaching this way wrong? Thanks!
Yes, jQuery has a "serializeArray()" method that does pretty much what you ask for.
It returns an array like:
[ { name: "something", value: "whatever" }, { name: "another_one", value: 22 } ]
You can turn that into an object like this:
var arr = $('#form_id').serializeArray(), obj = {};
for (var i = 0; i < arr.length; ++i)
obj[arr[i].name] = arr[i].value;
If a name appears more than once in a form, then its "value" will be an array of values from the separate fields.
$data = $("form").serialize(); // will return query string
$data = $("form").serializeArray(); // will return array
(Details here)
You can use the $('#form').serializeArray() method in order to get the array passed to the POST request.
You can then edit the object you receive normally.

jQuery .getJSON return into array variable & json array manipulation

is there any way I can get the return of $.getJSON into a variable array?
I know its async and out of scope, but I will use it inside ajax callback, I just need to get all the values first and check them against another array.
Something like:
$.getJSON('itemManager.php?a=getItems', function(data){
// itemArray = new Array(data);
// idsArray = new Array(data.id);
for (var i in someOtherArray){
if($.inArray(i, idsArray) == -1){
// do something...
// get jason variable by id?
// itemArray[i].someVariable
}
}
}
EDIT: JSON structure
[{"id":"786","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"787","user_id":"1","seller_id":"2","address_id":"1","time":1299852115,"publicComment":null,"personalComment":null},
{"id":"785","user_id":"1","seller_id":"2","address_id":"1","time":1299852114,"publicComment":null,"personalComment":null},
{"id":"784","user_id":"1","seller_id":"2","address_id":"1","time":1299852113,"publicComment":null,"personalComment":null},
{"id":"783","user_id":"1","seller_id":"2","address_id":"1","time":1299852111,"publicComment":null,"personalComment":null}]
This is basically the idea.
Get all the values
Isolate the id values of JSON objects
Loop another array
Check if json id is inside the other array
Access other json variables by id value
There are various solutions here I guess, but I'm looking for something with minimal code.
With the given information, there is not shortcut to test the existence of IDs. You really have to loop over everything. However you can improve a bit by creating an id => object mapping:
$.getJSON('itemManager.php?a=getItems', function(data){
var items = {};
for(var i = data.length; i--; ) {
items[data[i].id] = data[i];
}
for (var j = someOtherArray.length; j--; ){
var item = items[someOtherArray[j]];
if(item){
// do something with `item`
}
}
}
It woud be even better if you create this structure on the server already, then it would be:
$.getJSON('itemManager.php?a=getItems', function(data){
for (var j = someOtherArray.length; j--; ){
var item = data[someOtherArray[j]];
if(item){
// do something with `item`
}
}
}
You should also consider which arrays will contain more elements, data or someOtherArray and adjust your data structures such that you loop over the smaller array only.
Update:
To create the appropriate structure on the server with PHP, you have to create an associate array.
So at the point where you add an object to the array, you should not do
$items[] = $obj;
but
$items[$obj->id] = $obj; // or $obj['id'] if you have an array
If you get an array as your JSON response then your data variable in your callback is an array, no need to do anything with it.
If you get an object as your JSON response as the data.id in you example might suggest, and some of it's values is an array, then just use data.id as an array, or use var array = data.id; if that is more convenient for you.
Remember that data in your callback is just whatever you got as JSON. It can be an object (which is an associative array), an array, a string, a number, or a true, false or null value. If it is an object you access it using data.key, if it is an array you access it using data[index]. I say it because I suspect that you might be confusing arrays with objects here.

Categories

Resources