own array + jQuery.serializeArray() + post as json - javascript

I get data is undefined, i guess i can't ['productId'] in an array, but i think i need this structure in the json, i tried a couple of variation but it never was, what i needed
i just want to send a json via ajax.
jQuery(':checked').each(function(i){
data[i]['productId'] = jQuery(this).parent().find('.productId').val();
jQuery(this).parent().find('.attrGrp').each(function(j){
data[i]['attrGrps'][j]['uid'] = jQuery(this).find('.active').attr('id');
data[i]['attrGrps'][j]['amount'] = jQuery(this).parent().find('.amount').val();
});
});
jQuery.post(newSession, {json: data.serializeArray()});
is there any better way for doing it? or how can i make it work?
help appreciated ;/

You need to initialize arrays and objects before using them. String indexes are only possible with objects. Try this:
var data = [];
jQuery(':checked').each(function(i)
{
data[i] = {};
data[i].productId = jQuery(this).parent().find('.productId').val();
data[i].attrGrps = [];
jQuery(this).parent().find('.attrGrp').each(function(j)
{
data[i].attrGrps[j] = {};
data[i].attrGrps[j].uid = jQuery(this).find('.active').attr('id');
data[i].attrGrps[j].amount = jQuery(this).parent().find('.amount').val();
});
});
Alternatively you could use jQuery().serialize, post everything in the form and sort it out on the server.

Related

Encoding an object instead of each property

Very late to the game -
I've just now started to think about XSS on my website. Unfortunately, in several places I created objects that I pass via Ajax:
var params = {};
params.firstName = $("#firstName").val();
params.lastName = $("#lastName").val();
$.ajax({url:url, data:params}).done();
Anyone can write in executable JS. Now, from what I've read, I can easily remedy this situation by doing this:
var params = {};
params.firstName = encodeURIComponent($("#firstName").val());
params.lastName = encodeURIComponent($("#lastName").val());
$.ajax({url:url}, data:params).done();
But instead of going through every place I create an object and wrapping every field in encodeURIComponent --- is there any way to simply escape characters directly on the params instead of on each property?
Thanks for any helpful tips.
Update: When Content-Type:application/x-www-form-urlencoded; charset=UTF-8 then form data is automatically encoded.
Something like this would work:
function encodeParams(data) {
Object.keys(data).forEach(function(key) {
data[key] = encodeURIComponent(data[key]);
});
return data;
}
You could use like so:
var params = encodeParams({
firstName: $('firstName').val(),
lastName: $('lastName').val()
});
ajax(...)

Store values in javascript object with same keys

I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];

when saving an array of objects as a JSON, I need to use the following format in Sample.txt to not run into parsing errors:

when saving an array of objects as a JSON, you need to use the following format in Sample.txt to not run into parsing errors:
[{"result":"\"21 inches = 21 inches\"","count":1},{"result":"\"32 inches = 32 inches\"","count":2}]
I'm new to JSON and searching over this for since last 4 days. I tried different approaches of storing an array of objects but no success. My first and simplest try is like this:
function createData() {
//original, single json object
var dataToSave = {
"result": '"' + toLength.innerText +'"',
"count": counter
};
//save into an array:
var dataArray = { [] }; //No idea how to go ahead..
var savedData = JSON.stringify(dataToSave);
writeToFile(filename, savedData); //filename is a text file. Inside file, I want to save each json object with , in between. So It can be parsed easily and correctly.
}
function readData(data) {
var dataToRead = JSON.parse(data);
var message = "Your Saved Conversions : ";
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
}
To make an array from your object, you may do
var dataArray = [dataToSave];
To add other elements after that, you may use
dataArray.push(otherData);
When you read it, as data is an array, you can't simply use data.result. You must get access to the array's items using data[0].result, ... data[i].result...

Importing multiple CSV files in Javascript

I need to import 8-10 CSV files into some JS code. Each file has about 8 different columns. I would like to store this information in an object (possibly identifying the object based on one of the ID fields). The problem is, the easiest way I can think of looks like this:
var authorArr = [];
d3.csv("data/authors.csv", function(csv) {
csv.forEach(function(d) {
authorArr[d.record_id] = [];
d.record_id = +d.record_id;
d.name = d.name
d.name_inverted = d.name_inverted;
d.role = d.role;
d.sequence = +d.sequence;
d.is_person = d.is_person;
authorArr[d.record_id] = d.name;
authorArr[d.record_id] = d.role;
etc...
Surely this cannot be the quickest way...Also, there are quite a bit of duplicated record_id values as well, so every time there is a repeat, I would lose all previous data with my horrible approach.
I'm not sure if that's enough detail. If not, I would be glad to add more.
You can use a temporary variable for the new/current record. Your example also looks like you do not want an array (with gaps) but a map. Here is how I would load the data:
var authorMap = {}
var loadCSV = function(file){
d3.csv(file, function(error, data) {
data.forEach(function(d) {
var a = authorMap[d.record_id] = {}
a.record_id = d.record_id
a.name = d.name
a.role = d.role
});
});
}
loadCSV("file1.csv")
loadCSV("file2.csv")

question regarding serializeArray and passing into url

I am not totally familiar with javascript, jquery.
I am trying to do the following. Note a-f are names for the dropdown menus. Can someone help clarify? thanks
var a_params = $("#a").serializeArray();
var b_params = $("#b").serializeArray();
var c_params = $("#c").serializeArray();
var d_params = $("#d").serializeArray();
var e_params = $("#e").serializeArray();
var f_params = $("#f").serializeArray();
params.push({ name: 'menu_mode', value: '2-1' });
$.get("./scripts/model.cgi", a_params,b_params,c_params,d_params,e_params,f_params, function(data){
$("#grapharea").html(data);
$("#prog").html(" ");
});
More Comments: in the cgi script i am dumping the inputs to see if i am receiving the values from the a-f_params but this isn't the case. Any ideas why?
You have to create 1 array(or jquery-object in this case) from all object's, and serialize this array.
$('#a,#b,#c,#d,#e,#f').serializeArray();
But this is only needed, if you dont want to serialize e.g. all input-fields.
Otherwise you can use simply
$('#form').serializeArray();

Categories