make an array with the values of similar keys from JSON array - javascript

I have an array in JSON array format. I want to extract the values of common keys and make a new array with this.
I've tried this
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
where sale_date and total are the keys.
but this code returned an array of undefined objects.
my array named data looks like
{"sale_date":"2017-12-26 11:05:05","total":"500"}{"sale_date":"2017-12-26 11:05:18","total":"500"}
I'm expecting two arrays date[2017-12-26 11:05:05, 2017-12-26 11:05:18 ] and amt[500, 500]
I'm getting data as a ajax response From the code below.
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$db_data = $row;
print json_encode($db_data);
}
}
And this how my ajax request looks like
$(document).ready(function(){
$.post("ajax-req-handler.php",
{
key: "draw-line-chart"
},
function( data ){
console.log(data);
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
});
});

var data = [
{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}
];
var date = [];
var amt = [];
for(var i in data){
console.log(i);
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
PHP Code :-
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
$data = array();
if($result->num_rows>0){
while($row=$result->fetch_assoc()){
$db_data[] = $row;
}
}
echo json_encode($db_data);
Ajax Request :-
$(document).ready(function(){
$.post("ajax-req-handler.php",
{
key: "draw-line-chart"
},
function( data ){
console.log(data);
data = JSON.parse(data);
var date = [];
var amt = [];
for(var i in data){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
});
});

You need to encapsulate your object between array
var data = [{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}]
var date = [];
var amt = [];
for(var i=0;i<data.length;i++){
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);

This is not a JavaScript but PHP issue.... you are sending invalid JSON. The following:
{"sale_date":"2017-12-26 11:05:05","total":"500"}{"sale_date":"2017-12-26 11:05:18","total":"500"}
Should actually look like:
[{"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"}]
You need to change your PHP code to this:
// Add content type so that jQuery knows you're sending JSON
header("Content-Type: application/json");
$sql = "SELECT sale_date, total FROM customers";
$result = $conn->query($sql);
$db_data = array();
while ($row = $result->fetch_assoc()) {
$db_data[] = $row;
}
echo json_encode($db_data);
Sending Content-Type header should be enough but you should also change your jQuery code just to be sure:
$(document).ready(function() {
$.post("ajax-req-handler.php", {
key: "draw-line-chart"
}, function(data) {
console.log(data);
var date = [];
var amt = [];
for (var i in data) {
date.push(data[i].sale_date);
amt.push(data[i].total);
}
console.log(date);
console.log(amt);
}, "json");
// the 4th parameter is dataType set to json
});

//Hope this will be of help.
var data = [ {"sale_date":"2017-12-26 11:05:05","total":"500"},{"sale_date":"2017-12-26 11:05:18","total":"500"} ];
var date = amt = [];
X = 0;
while (x < data.length) {
date.push(data[x].sale_date);
amt.push(data[x].total);
x++;
};
console.log(date);
console.log(amt);
Explanation:
line 1 is the array of objects which represent the data u are pulling from ur json data.
Line 2 is the declaration of the two variable arrays which is assigned to and empty array. So, I used the short form of declaring multi-variable on the same line of statement.
Line 3 is the initialization of the counter "x" that will help break the While Loop once the it counts to the last Object in the array "data".
Line 4. Then the While Loop which keep iterating through the array " data". The conditional statement there always check if the counter "x" is < (less than) the length of the array In each iteration it.
Line 5. In the While Loop block code using the counter "x" as index of the array to access the property "sale_date" of the object in that array index and push it to the array "date" (I.e adding it at the end of the array "date").
Line 6. The same as line 5, accessing the property total in that index of the array " data" and push it to array "amt".
Line 7 increment the counter " x" by 1 and assign it to back to x which is used to reevaluate the While Loop.
Line 8 & 9 is just a console log that displays what's in date and amt respectively.
Thanks
Hope this makes sense to u... Please, Let me know your feedback.

Related

using items from php array to change css

UPDATE: I should add the overall goal is to change the background of a cell based on the 1st query and the border based on the second query then when the beacon stops being pulled in on the 1st query the background goes back to grey
I am trying to use data pulled in from mysql to change the background of table cells, after some modification to my code it no longer works all though the data is still being passed through via Ajax using code below:
before the modification i only used 1 array but since adding 2 arrays as an outer array i can't get it to work, also i i add an item to the console log i just get undefined e.g. item.beacon would normally return a number instead it returns undefined in the console log although it is in the array.
data
I have included the data as a picture to save using to much text
html
<script>
$(document).ready(function() {
for (var i = 0; i < 12; i++) {
var row = $('<tr>').appendTo("#zoning tbody");
for (var j = 1; j < 11; j++) {
$(`<td class='${i * 10 + j}'>${i * 10 + j}</td>`).appendTo(row);
}
}
$.get('php/test.php', function(response) {
console.log(response);
var row;
$.each(response, function(index, item) {
console.log(item);
$(`td.${beacon}`).css('background-color', location).toggleClass('coloured');
});
});
function updateTable() {
//console.log('function called');
$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
$.get('php/test.php', function(response) {
$.each(response, function(index, item) {
console.log(beacon);
//$('td.coloured').css('background-color','#8F8F8F').toggleClass('coloured');
$(`td.${beacon}`).css('background-color', location).toggleClass('coloured');
});
});
}
var updateTableInterval = setInterval(updateTable, 5000);
});
</script>
php
# header('Content-Type: applicaton/json');
$sql1 = 'SELECT
*
FROM
(SELECT
beacon,location,date,
COUNT(location) AS counter
FROM `test`.`test`
WHERE `date` = CURDATE() and `time` > NOW() - interval 40 second
GROUP BY beacon) AS SubQueryTable
ORDER BY SubQueryTable.counter DESC;';
$result1 = $conn->query($sql1);
$rows1 = $result1->fetch_all(MYSQLI_ASSOC);
$sql2 = "SELECT beacon,location,TIME_FORMAT(TIMEDIFF(max(`time`),min(`time`)), '%i.%s')
AS `delivery_avg`
FROM `test`.`test`
where date = CURDATE()
and time > now() - INTERVAL 30 MINUTE
group by beacon";
$result2 = $conn->query($sql2);
$rows2 = $result2->fetch_all(MYSQLI_ASSOC);
$result = array(
'query1' => $rows1,
'query2' => $rows2,
);
echo json_encode($result);
$conn->close();
Here's example code that should solve this:
$.getJSON('php/test.php', function(response) {
$.each(response.query1, function(index, item) {
console.log(item);
// use first array's item.beacon, item.location, etc.
});
$.each(response.query2, function(index, item) {
console.log(item);
// use second array's item.beacon, item.location, etc.
});
});

Create an associative array in jquery using php array

I need to create an assosiative array in jQuery from PHP.
Here is my script so far. selectedStoresDict is json encoded array with values ["Lahore", "Islamabad"]
var selectedStores = <?php echo $selectedStoresDict; ?>;
var data = {};
for( i = 0 ; i <= selectedStores.length; i++) {
data['id'] = i;
data['text'] = selectedStores[i];
}
console.log(data, "Hello, world!");
However my console is showing that its not an array. I want something like this:
[{ id: 1, text: 'Lahore' }, { id: 2, text: 'Islamabad' }]
I think this should be a JS question instead of a PHP one, but here you have. You were almost there:
var selectedStores = <?php echo $selectedStoresDict; ?>;
var data = [];
for( i = 1 ; i <= selectedStores.length; i++) {
data.push({
id: i,
text: selectedStores[i]
});
}
console.log(data, "Hello, world!");
An array in JS is represented with [], so you need to initialize it like that, then just push the info (in this case, and object with keys and values). Also for ids starting with 1, you must initialize i = 1.
No need to loop thru.
Just json_encode the array
<?php
$selectedStoresDict[] = array("id"=>1,"text"=>"Lahore");
$selectedStoresDict[] = array("id"=>2,"text"=>"Islamabad");
?>
<script>
console.log('<?php echo json_encode($selectedStoresDict); ?>');
</script>

How to convert variable to two dimensional array using java script

I have a variable which contains data like this
var values = "VItDTotal,123,234,234,2345,1234,123,435,10,TestCase,123,234,234,2345,1234,123,435,5"
and I want to convert this string of data to a two dimensional array like this
[VItDTotal,123,234,234,2345,1234,123,435,10] //1st row
[TestCase, 123,234,234,2345,1234,123,435,5] //2nd row
How can I convert a JS variable to a two dimensional array?
I want to append these values to a datatable, how can I achieve this by using jQuery?
I hope this might help...
var values = "VItDTotal,123,234,234,2345,1234,123,435,10,TestCase,123,234,234,2345,1234,123,435,5"
var splittedArray = values.split(',')
var resultArray = new Array();
var resultKey = -1;
for(var i=0; i<splittedArray.length; i++) {
if(isNaN(splittedArray[i])) {
resultKey++;
resultArray[resultKey] = new Array();
resultArray[resultKey].push(splittedArray[i])
} else {
resultArray[resultKey].push(splittedArray[i])
}
}
I work this way:
//get the index where ",TestCase" is
var index = values.indexOf(",TestCase");
//create two arrays to the values
var part_one = [], part_two = [];
//slice the value from 0 to index and push part one
part_one.push(values.slice(0,index));
//slice the value from index+1 to the end and push part two
part_two.push(values.slice(index+1, values.length));
Not my favourite, but, are you after something like this?
var values = ["VItDTotal",123,234,234,2345,1234,123,435,10,"TestCase",123,234,234,2345,1234,123,435,5];
var vals = [values.
join(",").
replace(/,([a-z]+)(?!.*[a-z]+)/gi, " devider $1").
split(/\s+devider\s+/gi)];
console.log(vals);

How to fill javascript array from ajax data result

I have scripts like this.
javascript
$.ajax({
url : "load_data_person.php",
dataType:"json",
success:data_person(arrData)
});
function data_person(info_person){
var attr = [];
var len = [];
for(j=0;j<info_person.length;j++){
attr.push(info_person[j][0]);
len.push(info_person[j][1]);
}
return [attr, len];
}
How can I insert data to variable info_person like this:
info_person = [['fname',20],['lname',15],['addr',50]];
so I can get each value of attr and len?
Here is the script for data_person.php
<?php
$qStrPerson = mysql_query("SELECT atribut, len FROM tb_person ORDER BY fname ASC");
$arrFullPerson = array();
while($rStrPerson = mysql_fetch_array($qStrPerson)){
$arrFullPerson[] = array($rStrPerson[atribut],$rStrPerson[len]);
}
echo json_encode($arrFullPerson);
// it will return like this : Array 0 : ['fname', 20], Array 1 : ['lname',15], Array 2 : ['addr',50]];
?>
Thank you for your help.
You can use simple jquery to convert the JSON to Javascript array
var array = JSON.parse(your json string);
You can just format the array as you wanted in the server side and then echo it. While receiving the ajax response, you can simply
var info_person = json.parse(arData);
to convert the json-encoded value into javascript array.

Adding for loop results to an array and displaying sum of added elements after the last loop

I have to get some records based on weekly basis for the last weeks, and have to add values from records of one week to an array. So, I declared 6 arrays to store 6 weeks records. My code is:
var w_0 = [];var w_1 = [];var w_2 = [];var w_3 = [];var w_4 = [];var w_5 = [];
var myTotal = 0;
var arr_name = "";
for(var j=0;j<=5;j++)
{
var start_date="";
var end_date="";
//code to fetch the records added between start_date,end_date
//there may be more that one record
var count = getRecordCount(); //My function
//following loop is to fetch value from a record
for(var i=0;i<count;i++)
{
var val1 = getRecordByIndex(i).getValue("rem_val"); //getRecordByIndex() and getValue() are our pre-defined functions.
//here I want to push the values into the array w_0
arr_name = "w_"+j;
[arr_name].push(val1); //this is not working
alert([arr_name]); //showing 'w_0'
}
//and here I want to sum all the array elements when i reaches its maximum
for(var a=0;a<[arr_name].length; a++){
myTotal += parseInt([arr_name][a]);
}
alert("Total value of week"+j+"="+parseInt(myTotal));
}
How can I add values of inner loop to the array based on outer loop?
Any time you find yourself creating variables with sequentially numbered names, you should probably be using an array instead.
var w = [[], [], [], [], []];
Then, wherever you tried to use [arr_name] to refer to a particular w_j variable, you should use w[j].
for(var j=0;j<=w.length;j++)
{
var cur_w = w[j];
var start_date="";
var end_date="";
//code to fetch the records added between start_date,end_date
//there may be more that one record
var count = getRecordCount(); //My function
//following loop is to fetch value from a record
for(var i=0;i<count;i++)
{
var val1 = getRecordByIndex(i).getValue("rem_val"); //getRecordByIndex() and getValue() are our pre-defined functions.
cur_w.push(val1);
alert(cur_w);
}
//and here I want to sum all the array elements when i reaches its maximum
for(var a=0;a<cur_w.length; a++){
myTotal += parseInt(cur_w[a]);
}
alert("Total value of week"+j+"="+parseInt(myTotal));
}
If you want to dynamically manipulate global variables you can use window prefix:
arr_name = "w_"+j;
window[arr_name].push(val1); // This should work

Categories

Resources