I need some help! Im retrieving some values from mySQL database using an external 'grabber'.
<?php
$datapiechart = file_get_contents("url which retrieves the values from MySQL");
?>
Which results in:
[{ "Name1": 62, "Name2": 42, "Name3": 19, "Name4": 7, "Name5": 6, "Name6": 4, "Name7": 1, "Name8": 4, "Name9": 3, "Name10": 1, "Name11": 1, "Name12": 0 }]
Then I want to select the values in this array.
<SCRIPT>
dataObjectdatapiechart = <?php echo $datapiechart; ?>
</SCRIPT>
<script> dataObjectdatapiechart.Name1</script>
I don't get whats going wrong here.
dataObjectdatapiechart is an array (with only one element), so you need to access it's contents using an indexer:
var item = dataObjectdatapiechart[0]; // Retrieve the object from the array
var name1 = item.Name1;
var name2 = item.Name2;
var name3 = item.Name3;
//etc.
Use
dataObjectdatapiechart[0].Name1
The Object { "Name1": 62, "Name2": 42, "Name3": 19, "Name4": 7, "Name5": 6, "Name6": 4, "Name7": 1, "Name8": 4, "Name9": 3, "Name10": 1, "Name11": 1, "Name12": 0 }
is at 0th position of the array.
Related
I get a json from an API I wrote. This json contains some values and one of this should be appended to another json.
The json to append the data to is the following:
originalOrder = {
"nome": 1,
"cognome": 2,
"mail": 3,
"telefono": 4,
"cf": 5,
"data": 6,
"ora": 7,
"cellit": 8,
"cellex": 9
};
The data I need to append is:
var toAppend = data.name;
and if i echo the toAppend value it shows the correct value. Say for example that toAppend echoes dummyData. I want the json to be at the end:
originalOrder = {
"nome": 1,
"cognome": 2,
"mail": 3,
"telefono": 4,
"cf": 5,
"data": 6,
"ora": 7,
"cellit": 8,
"cellex": 9,
"dummyData": 10
};
So I also calculate the length of the array:
var lunghezza = parseInt(originalOrder.length);
lunghezza = lunghezza +2;
and then I add the new item to the array:
originalOrder.toAppend=lunghezza;
but the array ends up like this:
originalOrder = {
"nome": 1,
"cognome": 2,
"mail": 3,
"telefono": 4,
"cf": 5,
"data": 6,
"ora": 7,
"cellit": 8,
"cellex": 9,
"toAppend": NaN
};
so I have two issues:
i get the variable name instead of the variable value
I get not a number instead of 10 (I tried also to force it with parseInt but seems with no luck)
What am I doing wrong here?
Edit:
if I do
var toAppend = data.nome;
console.log('toAppend: '+toAppend);
in console.log:
toAppend: dummyData;
that is the expected behaviour
Thanks!
originalOrder is an object and for this reason, to get the number of keys (i.e., "the length of the object"), you need:
Object.keys(originalOrder).length
To add a key with the value of the var toAppend you need to write:
originalOrder[toAppend] = lunghezza
To use variable value as a key to an object you can use the square bracket in javascript.
const obj = {
"hello": "world"
};
const key = "value";
obj[key] = "any value";
console.log(obj)
will print
{
"hello": "world",
"value": "any value"
}
Also, you can't use length properties on an object. However, you can get list of keys of an object, then get the length.
console.log(Object.keys(obj).length);
will print
2
Hope this helps
Why doesn't the value of variable show? I think it should be 1 or 0 depending on value inside of variable bayar, but why its doesn't work
I've tried to do anything that I can do but it doesn't work like it try to change several code but it doesn't work.
Here's my controller code:
public function generated(){
$data=DB::table("tb_trx_perhitungan_bunga_simpanan")
->selectRaw('trx_bulan')
->get();
return view('crud.form.cobaNampilin',compact('data'));
}
And here's my JavaScript and jQuery code:
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var a;
var array = {!! json_encode($data) !!};
var i;
var b;
$('#bulan').keyup(function(){
var bayar=parseInt($('#bulan').val());
for(i=0;i<=array.length;i++){
if(bayar==array[i].trx_bulan){
a=1;
}
else{
a=0;
}
}
$('#hasil').val(a);
});
});
</script>
I expected the output is 1 or 0
The content of var array I think should be [trx_bulan 1],[trx_bulan 2],[trx_bulan 3],[trx_bulan 4],[trx_bulan 5],[trx_bulan 6] because content of array is an array object. I read that on the website so that's why I use array[index].trx_bulan] to call the value of each index.
Here's the screenshot of table data:
So if you have a data table like:
Then consider the following code:
$(function() {
var a = 0;
/*
In laravel use:
var data = {{json_encode($data)}};
it will translate to something like:
*/
var data = [{
id: 27,
trx_bulan: 1,
trx_tahun: 2018,
tangal_proses: "2018-12-09 07:23:00",
persentase_bunga: 0.2,
id_user: 3
}, {
id: 28,
trx_bulan: 2,
trx_tahun: 2018,
tangal_proses: "2018-12-09 03:42:39",
persentase_bunga: 0.2,
id_user: 3
}, {
id: 29,
trx_bulan: 3,
trx_tahun: 2018,
tangal_proses: "2018-12-09 03:43:43",
persentase_bunga: 0.2,
id_user: 3
}, {
id: 30,
trx_bulan: 4,
trx_tahun: 2018,
tangal_proses: "2018-12-09 03:44:06",
persentase_bunga: 0.2,
id_user: 3
}, {
id: 31,
trx_bulan: 5,
trx_tahun: 2018,
tangal_proses: "2018-12-09 03:45:40",
persentase_bunga: 0.2,
id_user: 3
}, {
id: 33,
trx_bulan: 6,
trx_tahun: 2018,
tangal_proses: "2018-12-09 06:32:38",
persentase_bunga: 0.2,
id_user: 3
}];
$('#bulan').keyup(function(e) {
var bayar = parseInt($('#bulan').val());
a = 0;
$.each(data, function(k, v) {
if (bayar == v.trx_bulan) {
console.log("Hit", v);
a = 1;
}
});
$('#hasil').val(a);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="bulan" />
<br />
<input type="text" id="hasil" />
You may want to consider switching to type="number" or checking that the entry is a number value when the user types something.
Hope that helps.
It never return output because wrong loop condition, the loop for(i=0;i<=array.length;i++) will throw error and $('#hasil').val(a); will not executed.
TypeError: array[i] is undefined
It is because i index is out of range, use the < only
for(i=0; i<array.length; i++)
then if element with ID hasil is not <input> use .html()
$('#hasil').html(a);
And there are several ways to convert to JSON
#json Blade directive
var array = #json($data);
single Curly brackets
var array = {!! json_encode($data) !!};
using toJson()
var array = {!! $data->toJson() !!};
and native php
var array = <?php echo json_encode($array); ?>;
Is it possible to make a multidimensional array in javascript?
It should look like this:
$cars = array
(
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
But I need to use $cars.push(); to first add all data for the first rows (the cars). Then the data "22", "15", "5" and "17". Then "18", "13", "2" and "15".
Then it should be printed in the same order as the original array (table-view).
EDIT
LIKE this:
var cars = [];
cars.push("Volvo", "BMW", "Saab", "Land Rover");
cars.push(22, 15, 5, 17);
cars.push(18, 13, 2, 15);
and print it like this to html
Volvo, 22, 18
BMW, 15 13
Saab, 5, 2
Land Rover, 17, 15
You could refer the documentation.
As #sampson suggested in the comment above in your case it is,
var cars = [
[ "Volve", 22, 18 ],
[ "BMW", 15, 13 ],
[ "Saab", 5, 2],
[ "Land Rover", 17, 15]
];
Is it possible to make a multidimensional array in javascript?
Yes, it is.
But that doesn't seem to be your question. Rather, your question seems to be, if I have an array of arrays, where the first subarray contains values for field 1, the second subarray contains values for field 2, and so on, then how do I re-organize this into in array of arrays where each subarray contains all fields for one object.
As another responder mentioned, this is array transposition. A simple way is:
function transpose(a) {
return a[0] . map((col, i) => a . map(row => row[i]));
}
Use this as:
var cars = [];
cars.push(["Volvo", "BMW", "Saab", "Land Rover"]);
cars.push([22, 15, 5, 17]);
cars.push([18, 13, 2, 15]);
console.log(transpose(cars));
You can rebuild the array with the change of position i and j. And you can switch it from one appearance to the other one.
function transpose(source, target) {
source.forEach(function (a, i) {
a.forEach(function (b, j) {
target[j] = target[j] || []
target[j][i] = b;
});
});
}
var cars = [["Volvo", 22, 18], ["BMW", 15, 13], ["Saab", 5, 2], ["Land Rover", 17, 15]],
pCars = [];
transpose(cars, pCars);
document.write('<pre>' + JSON.stringify(pCars, 0, 4) + '</pre>');
cars = [];
transpose(pCars, cars);
document.write('<pre>' + JSON.stringify(cars, 0, 4) + '</pre>');
I'm having difficulty creating some code that dynamically creates graphs:
The following code snippet helps create the graph:
xGrid: false,
legend: true,
title: 'Meetings and Hours Used',
points: [
[7, 26, 33, 74, 12, 49, 33, 33, 74, 12, 49, 33],
[32, 46, 75, 38, 62, 20, 52, 75, 38, 62, 20, 52]
],
And I've replaced the points section with this:
points: <%= getJson() %>
And my code behind has function:
public string getJson()
{
var publicationTable = new List<object>{
new { points = "[1,2,3,4,5,6,7,8]," }
};
return (new JavaScriptSerializer()).Serialize(publicationTable);
}
The javascript doesn't seem to be parsing - can anyone please help me :)
Try this.
public string getJson() {
var publicationTable = new[] {
new[] { 1, 2, 3, 4, 5 },
new[] { 6, 7, 8, 9, 10 }
};
return (new JavaScriptSerializer()).Serialize(publicationTable);
}
List<List<int>> lstMainArr = new List<List<int>>();
lstMainArr.Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.ToList<int>());
lstMainArr.Add(new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 }.ToList<int>());
Console.Write((new JavaScriptSerializer()).Serialize(lstMainArr));
points: <%= getJson() %>
This outputs whatever the return result type is, so for example:
points: 8 // getJson() returns int
points: test // getJson() returns a string
if you had done:
points = "[1,2,3,4,5,6,7,8],";
return points:
the result would be:
points = [1,2,3,4,5,6,7,8],
However you have:
var publicationTable = new List<object> {
new { points = "[1,2,3,4,5,6,7,8]," }
};
return (new JavaScriptSerializer()).Serialize(publicationTable);
So to determine the output, step through each outer to inner method/object.
Step 1: Serialization - Creates an empty string.
""
Step 2: Serialize List<Object> (basically a JavaScript array)
"[]"
Step 3: Serialize first anonymous Object:
"[{}]"
Step 4: Serialize first property :
"[{"points" : "[1,2,3,4,5,6,7,8],", }]"
No more properties, no more objects, serialization finished. This is not the JSON you were looking for.
I've been doing some research and am not getting anywhere. I have a situation where I need an array to contain a possibly variable number of arrays. Based on the example below, do you have any ideas?
var masterArray = [];
function PrepData(inVal) {
var amt = inVal.split("|");
for (var i = 0; i < amt.length; i++) {
// !!!Trouble area!!!
masterArray[i].push = amt[i];
};
}
What I'm doing is feeding 12 months' worth of data into this function, so PrepData runs 12 times each time I activate the calling function. The variable inVal can contain something like "9|9|0" or "9|123|470|1500|13". What I'm looking to do is split the incoming value on the pipe and store the results in amt. Then I want to feed each value from amt into individual arrays within masterArray. The good news is that inVal's length is constant once the first value is in, so if the first of 12 iterations splits into 3 pieces, the other 11 will also. To lay it out, here's what I would expect a typical run to produce given this input:
Oct: "1|2|1300"
Nov: "1|3|1400"
Dec: "2|5|1450"
Jan: "3|6|1900"
Feb: "4|8|2015"
Mar: "4|8|2020"
Apr: "19|38|3200"
May: "30|42|3500"
Jun: "32|50|5000"
Jul: "48|72|6300"
Aug: "50|150|7500"
Sep: "80|173|9000"
Once all twelve run through PrepData, I should have an array that contains this:
masterArray[0] == {1, 1, 2, 3, 4, 4, 19, 30, 32, 48, 50, 80} // All the numbers from the first section
masterArray[1] == {2, 3, 5, 6, 8, 8, 38, 42, 50, 72, 150, 173} // All the numbers from the second section
masterArray[2] == {1300, 1400, 1450, 1900, 2015, 2020, 3200, 3500, 5000, 6300, 7500, 9000} // All the numbers from the third section
If each month contained a string with 5 sections, then masterArray would need to be able to go from [0] to [4], and so on. The trouble area above isn't working, so I'm obviously missing something, but don't know what that might be.
Here is the updated code
var masterArray = [];
function PrepData(inVal){
var amt = inVal.split("|");
for (i in amt) {
if(typeof masterArray[i] == 'undefined'){
masterArray[i] = [];
}
masterArray[i].push(amt[i]);
}
}
There is a need to check first if an array is defined in each index in masterArray. If it's not defined then you need to initialize it to a blank array. Then you can push the splited value and you get the same result
masterArray[0] == {1, 1, 2, 3, 4, 4, 19, 30, 32, 48, 50, 80}
masterArray[1] == {2, 3, 5, 6, 8, 8, 38, 42, 50, 72, 150, 173}
masterArray[2] == {1300, 1400, 1450, 1900, 2015, 2020, 3200, 3500, 5000, 6300, 7500, 9000}
Here is a demo in js fiddle