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);
});
Related
I try to take object from my controller, when I console.log(response) it show the value correctly which is in
[
{
"itemValue":100,
"itemUnit":"2"
}
]
unfortunately I try to use the object like response.itemValue when I console it show undefined. I try var object = response. during the console it show the same value. Please I want to use the response data.
if(itemID){
$.ajax({
type:'POST',
url:'?syspath=ajax&controller=ajax&action=getActItemDose',
data: { 'itemId': itemID, 'itemType': itemType },
success:function(response){
// var obj = jQuery.parseJSON(data);
console.log(response);
var object = response;
var value = object.itemValue;
var unit = object.itemUnit;
console.log(object);
console.log(value);
}
});
}
This is controller where I encode the object into Json
$row = $getProcess->fetch();
$object[] = array(
'itemValue' => $row['each_dose'],
'itemUnit' => $row['unit_dose']
);
echo json_encode($object);
I recommend using the jQuery library. For parsing JSON, simply do
var obj = JSON.parse(data);
// Accessing individual value from JS object
alert(obj.itemValue);
alert(obj.itemUnit);
It worked, by changing this few item
$object[] = array();
into
$object = array();
and JSON.parse(data)
var object = JSON.parse(data);
value = object.itemValue;
unit = object.itemUnit;
Your response is an array. So you need to access it like
response[0].itemValue
or you can loop through the array
response.forEach(element => {
console.log(element.itemValue);
});
Below is the example
const response = JSON.parse(`[
{
"itemValue":100,
"itemUnit":"2"
}
]
`);
response.forEach(element => {
console.log(element.itemValue);
});
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"}}
I have a function that is supposed to check old data against data. I am parsing data and oldData to get a JSON object respectively as dbData and formData are simply strings containing ID's and values for the HTMML form. The purpuse of the function is to check if the user has made any textchanges some textareas in the HTML form. I want to do this by checking the ID for each textarea and then check if the value in formData and Data are the same. In that case no change has been made and the function will return true.
The data string im parsing looks something like this:
"[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\Apple \",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]"
So for example, i have to check the ID for "textarea1" in dbData and formData and then check if the value is the same. Can this be done using wildcard or is there a better way to archive this?
function CheckValues() {
var isChanged = false;
var formData = $.parseJSON(data);
var dbData = $.parseJSON(oldData);
if(formData !== dbData) {
var isChanged = true;
}
return isChanged;
}
The code shown below works in IE9+, Chrome, FireFox but other
browsers yet to test. The example shows two different values, data and
OldData - data contains "Tea" where as OldData contains "OldTea" so
isChanged flag is true.
function CheckValues() {
var data = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"Tea\"}";
var oldData = "{\"disable\":false,\"textarea1
\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3
\":\"Milk\",\"textarea4\":\"Coffe\",\"textarea5\":\"OldTea\"}";
var formData = JSON.parse(data);
var dbData = JSON.parse(oldData);
var oFormData = Object.keys(formData);
var oDbData = Object.keys(dbData);
var isChanged = false;
if (oFormData.length === oDbData.length)
{
for (var i = 0; i < oFormData.length; i++) {
var propName = oFormData[i];
if (typeof (dbData[propName]) === "undefined") {
isChanged = true;
break;
}
else {
if (formData[propName] !== dbData[propName]) {
isChanged = true;
break;
}
}
}
}
}
I'm trying to get my array of URL's to run through a JQuery .get function to get the site's source code into one string outside of the function. My code is below.
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var get = $.get(fetch, function(sourcecode) {
sourcecode = fetch;
}
I need the sourcecode variable to be the combination of source code on all of the URLs in the array.
You need to put a variable outside of the function, something like this data variable below and append to it with +=:
var URL = ["http://website.org", "http://anothersite.com"];
var array = URL.map(function(fetch) {
var data = null;
var get = $.get(fetch, function(sourcecode) {
data += fetch;
}
}
Try this like,
var URL = ["http://website.org", "http://anothersite.com"];
var array = $(URL).map(function(fetch) {
var data='';
$.ajax({
url:fetch,
async:false,
success : function(d){
data=d;
}
});
return data;
}).get();
Since you're using jQuery, I suppose that jQuery.each() may be a better way to iterate over the array.
var URL = ["http://website.org", "http://anothersite.com"];
var str = [];
$.each(URL, function(index, fetch) {
$.get(fetch, function(sourcecode) {
str.push(sourcecode); // if you want an array
})
});
str.join(''); // if you want a string
console.log(str);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
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();