I am receiving data filled in from a form, but before posting to the server I need to prepend a key
> data
Object {rate: "300", identifier: "ZDA"}
Then I need to generate a unique key such as "OTNmam1JUkM=". The key is generated from a function like:
key = generateKey();
and prepend it to the object so I end up with
Object {"OTNmam1JUkM=": {rate: "300", identifier: "ZDA"}}
Any help would be appreciated... Please note I am using angular in an Ionic cross platform app.
var newData = {};
newData[generateKey()] = data;
You can use expressions when use with [].
It's really simple like:
var key = generateKey();
var oldData = data;
data = {};
data[key] = oldData;
See it here:
var data = {rate: "300", identifier: "ZDA"};
var key = generateKey();
var oldData = data;
data = {};
data[key] = oldData;
function generateKey() {
return 'iAmRandomISwear';
}
alert(JSON.stringify(data));
You don't mean prepend, but to nest it:
var data = {rate: "300", identifier: "ZDA"}; // or whatever you get from the form
var key = generateKey();
var nested = {};
nested[key] = data;
console.log(nested);
This will print out: {"OTNmam1JUkM=": {rate: "300", identifier: "ZDA"}}
Related
I'm trying to get values from json array inside a javascript. Below is the part of my javascript file. I'm using jsondata.value to get the values. It's displaying the json data correctly on the console, but jsondata.value is not working for getting the values.
I'm guessing that your "jsondata" is text in the DOM? If so, you want to grab the "string" in the DOM and Parse it into a valid JavaScript Object. To do so, you need to grab it appropriately:
var jsondata = document.getElementById("jsonArray").value;
Then you need to parse it
var jsondataObj = JSON.parse(jsondata);
At this point, jsondataObj is your data. If you want to populate this into your grid, simply inject it the way you wanted to. There is no need for XHRHttpRequest since you already injected your data into the DOM:
var gridOptions = { ... [your options here] };
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
new agGrid.Grid(gridDiv, gridOptions);
var jsondata = document.getElementById("jsonArray").value;
var jsondataObj = JSON.parse(jsondata);
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var parsedData = jsondataObj.map(function(obj) {
return Object.keys(obj).reduce(function(memo, key) {
var value = obj[key];
memo[key] = isNumeric(value) ? Number(value) : value;
return memo;
}, {})
})
console.log(parsedData);
gridOptions.api.setRowData(parsedData);
});
from controller Json is returned and in function i get an object which contains
{
"readyState":4,
"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{
"Success":0,
"Failed":0
},
"status":200,
"statusText":"OK"
}
How can I take Success and Failed values?
data.Successand JSON.parse(data) is not working
You dont need to parse that because that IS already an object:
var obj = {"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}","responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"};
var failed = obj.responseJSON.Failed;
var success = obj.responseJSON.Success;
var json_data = '{"readyState":4,"responseText":"{\"Success\":0,\"Failed\":0}",
"responseJSON":{"Success":0,"Failed":0},"status":200,"statusText":"OK"}';
var obj = JSON.parse(json_data);
alert(obj.responseJSON.Success); // for success that in responseJSON
alert(obj.responseJSON.Failed);
Thanks :)
I am getting an error in my .ajax() function when attempting to pass in the checkboxes
Here is the code:
if(typeof($post) !== 'undefined'){
var $fname = $($post).attr('name').toString();
var data = {$fname : []};
alert($post);
alert($fname);
$($post + ":checked").each(function() {
data[$fname].push($(this).val());
});
}else{
var data = null;
}
The error I am getting in firebug is: data[$fname].push($(this).val()); is undefined
$post is just a class name passed into the function.. in this case it's .del-checked
The alerts sucessfully alert me the class name, and the checkbox name... in this case it's del[]
How can I get this to work in order to pass it to the data option of $.ajax?
Because you can not use a variable as a key when creating a new object
var data = {$fname : []};
is the same thing as doing
var data = {"$fname" : []};
You need to create the object and add the key with brackets
var data = {};
data[$fname] = [];
You can't use variables as keys unless you use bracket notation
if (typeof($post) !== 'undefined'){
var $fname = $($post).attr('name');
var data = {};
data[$fname] = [];
$($post).filter(":checked").each(function() {
data[$fname].push( this.value );
});
}else{
var data = null;
}
What about:
var data = $($fname).serialize();
The MVC that creates the array of strings is
public JsonResult GetInvalidFilesAJAX(JQueryDataTableParamModel param)
{
string[] invalidFiles = new string[] { "one.xls", "two.xls", "three.xls" };
return Json(new
{
Status = "OK",
InvalidFiles = invalidFiles
});
}
And the javascript that should loop through and print out each string is
$.ajax(
{
type: 'POST',
url: 'http://localhost:7000/ManualProcess/GetInvalidFilesAJAX',
success: function (response) {
if (response.Status == 'OK') {
//Use template to populate dialog with text of Tasks to validate
var results = {
invalidFiles: response.InvalidFiles,
};
var template = "<b>Invalid Files:</b> {{#invalidFiles}} Filename: {{invalidFiles.value}} <br />{{/invalidFiles}}";
var html = Mustache.to_html(template, results);
$('#divDialogModalErrors').html('ERROR: The following files have been deleted:');
$('#divDialogModalErrorFiles').html(html);
How do I refer to the string in the array? The way above is not correct. All the example I find seem to be for when the Jason collection has property names.. in my case it is just a key value pair (I guess?)
There is no built in way. You must convert the JSON into an array or loop through the data yourself, e.g,
var data = JSON.parse(jsonString); // Assuming JSON.parse is available
var arr = [];
for (var i = 0, value; (value = data[i]); ++i) {
arr.push(value);
}
Alternatively:
var arr = [];
for (var prop in data){
if (data.hasOwnProperty(prop)){
arr.push({
'key' : prop,
'value' : data[prop]
});
}
}
And then to display it:
var template = "{{#arr}}<p>{{value}}</p>{{/arr}}";
var html = Mustache.to_html(template, {arr: arr});
This is assuming your JSON Object is one level deep.
When sending data via POST or GET with jQuery you use for format { name:"value" } so I thought, is there a way to do it with this kind of code:
var postdata = array();
postdata['name'] = "data";
$.post("page.php", postdata, function(data)
{
alert(data);
}
I tried this, and it doesn't seem to work. Is there a proper way to do this?
What you are trying to initialize is an object, not an array. You can initialize objects in two ways:
var postdata = {};
Or:
var postdata = new Object();
Then you can assign keys and values just like you intended:
postdata['name'] = "data";
Or:
postdata.name = "data";
You can also build your object in the initialization phase:
postdata = {
name: "data"
}