JavaScript Array Formatting problem - javascript

Can someone assist me with formatting this JavaScript array correctly? I am obviously missing something fundamental:
Javascript:
<script type="text/javascript">
var widths = new Array("225","320","480", "--");
var sidewalls = new Array();
sidewalls["225"] = new Array("65","55","45","40", "--");
var rims["225"] = new Array();
rims["225"]["65"] = new Array("R17", "--");
rims["225"]["55"] = new Array("R17","R18", "--");
rims["225"]["45"] = new Array("R17", "--");
rims["225"]["40"] = new Array("R18", "--");
sidewalls["320"] = new Array("70", "--");
var rims["320"] = new Array();
rims["320"]["70"] = new Array("R20","R24", "--");
sidewalls["480"] = new Array("65", "--");
var rims["480"] = new Array();
rims["480"]["65"] = new Array("R28", "--");
</script>
PHP used to generate the above JavaScript:
<?php while($row = mysql_fetch_array($result)) {
list($width, $sidewall, $rim) = explode("/",$row['meta_value']); $menu[$width][$sidewall][$rim] = 1; }
$widths = implode('","', array_keys($menu));
print "var widths = new Array(\"$widths\", \"--\");\n";
print "\nvar sidewalls = new Array();\n";
foreach($menu as $width => $sidewall_array) {
$sidewalls = implode('","', array_keys($sidewall_array));
print "sidewalls[\"$width\"] = new Array(\"$sidewalls\", \"--\");";
print "\nvar rims[\"$width\"] = new Array();\n";
foreach($sidewall_array as $sidewall => $rim_array) {
$rims = implode('","', array_keys($rim_array));
print "rims[\"$width\"][\"$sidewall\"] = new Array(\"$rims\", \"--\");";
}
} ?>
Thank you in advance for your help
Stu

You shouldn't be putting var in front of array assignments, just the initial definitions.
So var widths = ... is fine, but var rims["225"] = ... is incorrect and should just be rims["225"] = ....
Change your php; in the line of code that outputs that text remove the "var". Change this:
print "\nvar rims[\"$width\"] = new Array();\n";
To this:
print "\nrims[\"$width\"] = new Array();\n";
That will solve your problem. But really, this overall solution is not the best. You ought to consider looking into the json-encode php method.
You can take a fully-structured php data structure and with this one command convert to something that can be read by javascript. Try replacing your php with the below and see what happens (note that this is untested, but this is the basic idea):
<?php
while($row = mysql_fetch_array($result)) { list($width, $sidewall, $rim) = explode("/",$row['meta_value']); $menu[$width][$sidewall][$rim] = 1; }
print "var widths = " . json_encode(array_keys($menu)) . ";\n";
print "var sidewalls = " . json_encode($menu) . ";\n";
?>

Related

How to get MySQL data from PHP to Javascript via XMLHttpRequest and output the data chronologically?

I've managed to get the MySQL data that I needed in order for me to display it onto the notification's container. Now I have a problem at manipulating the data I needed. Instead of printing the objects one by one, it prints the same object at multiple times. Here is the source code.
PHP MySQL data getter
<?php
$host = 'localhost';
$username = 'root';
$password = '';
$dbname= 'notifications';
$dsn = "mysql:host=$host;dbname=$dbname";
$connection = new PDO($dsn, $username, $password);
$sql = 'SELECT * from notifications ORDER by date';
$query = $connection->prepare($sql);
$query->execute(PDO::FETCH_OBJ);
$array_list = [];
while($row = $query->fetch()){
array_push($array_list, $row);
}
echo json_encode($array_list);
?>
Javascript that gets the value of MySQL data from PHP file. Don't mind the long string, it's just an element that will be added up to the notification container when scrolled down.
var notificationContainer = document.getElementById('notifications-container');
notificationContainer.addEventListener("scroll", myPageScroll);
var index = -1;
function myPageScroll(){
var theScrollTop = notificationContainer.scrollTop;
var theScrollHeight = notificationContainer.scrollHeight;
var height = notificationContainer.clientHeight;
//THIS IS WHERE I HAVE A PROBLEM. IT PRINTS THE SAME OBJECT 5 TIMES.
if(theScrollTop + height >= theScrollHeight){
for(i = 0; i < 5; i++){
testing();
index = index + 1;
}
}
}
function testing(){
var xhr = new XMLHttpRequest();
xhr.open("POST", "data_getter.php");
xhr.onload = function(){
var jsvar = this.response;
jsvar = JSON.parse(xhr.responseText);
console.log(jsvar[index]);
notificationContainer.insertAdjacentHTML('beforeend', jsvar[index].notification_content);
};
xhr.send();
}
Html file
<div class="drop-down-container" id="notifications-container"></div>
<script src="header.js"></script>
Though when I printed the objects into the console, it has the organized data.
This is because when you get any fetch response the for loop has done iterating so index (inside the testing function) always has the same value. You need to pass index has parameter of testing function.
var notificationContainer = document.getElementById('notifications-container');
notificationContainer.addEventListener("scroll", myPageScroll);
var index = -1;
function myPageScroll(){
var theScrollTop = notificationContainer.scrollTop;
var theScrollHeight = notificationContainer.scrollHeight;
var height = notificationContainer.clientHeight;
//THIS IS WHERE I HAVE A PROBLEM. IT PRINTS THE SAME OBJECT 5 TIMES.
if(theScrollTop + height >= theScrollHeight){
for(i = 0; i < 5; i++){
testing(index); // pass index as parameter
index = index + 1;
}
}
}
function testing(index){ // index has been added as parameter
var xhr = new XMLHttpRequest();
xhr.open("POST", "data_getter.php");
xhr.onload = function(){
var jsvar = this.response;
jsvar = JSON.parse(xhr.responseText);
console.log(jsvar[index]);
notificationContainer.insertAdjacentHTML('beforeend', jsvar[index].notification_content);
};
xhr.send();
}

Using PHP array in the JS code in PDO

I'm trying to use a PHP array in the JS but encountered the error I don't know how to fix.
I was using this example (in my case - it's PDO, not mysqli.): Inserting MYSQL results from PHP into Javascript Array
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . '; charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$type_zagon = 1;
$id_kurat = 1;
$usid = 78;
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$num = $stmt1->fetchColumn();
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$gyvuliu_array = array();
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = $num;
}
$array_encode = json_encode($gyvuliu_array);
?>
<script>
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliai_fermoje = '<?php echo $array_encode; ?>';
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
I guess something is bad with the $num variable but I'm not sure.
EDIT:
I've changed the second for loop and it looks like it's working:
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
But I'm not sure if it's ok they aren't in the same row.
http://prntscr.com/ft4i9m
EDIT 2 After rickdenhaan's comment, it looks exactly how first for loop. Is it ok? Am I done?
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
You have to remove quotes, why? If you put the value in quotes that mean var gyvuliai_fermoje is a string not an array
Could You please try this once
$stmt1 = $pdo->prepare("SELECT GROUP_CONCAT(num) as nums FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
$row = $stmt1->fetch();
$array_encode = json_encode(explode(",",$row["nums"]));
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
$('.surinkti_produkcija_paserti_gyvulius').click(function() {
var gyvuliu_array = [1,2,3,4,5,6,7,8,9];
for (var i=0, l=gyvuliu_array.length; i<l; i++) { // WORKS
console.log(gyvuliu_array[i]);
}
// DOESN'T WORK (console returns f,a,l,s,e,f,a,l,s,e and so on..)
for (var i=0, l=gyvuliai_fermoje.length; i<l; i++) {
console.log(gyvuliai_fermoje[i]);
}
});
</script>
Try this
var gyvuliai_fermoje = <?php echo json_encode($array_encode, JSON_HEX_QUOT | JSON_HEX_APOS); ?>;
Problem solved! :) For future visitors, combined all this stuff you guys said, we have this code:
// PDO Connection
$pdo = new PDO('mysql:host=localhost; dbname=' . $db_name . ';
charset=utf8mb4', $db_user, $db_password);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Prepared statement with placeholders
$stmt1 = $pdo->prepare("SELECT num FROM tb_zagon_id WHERE status = :status
AND type = :type AND zagon_id = :zagon_id AND user_id = :usid ORDER BY num");
// Binding query result to the $num variable (1 is the first column)
$stmt1->bindColumn(1, $num);
// Executing query and replacing placeholders with some variables
$stmt1->execute(array(
':status' => 1,
':type' => $type_zagon,
':zagon_id' => $id_kurat,
':usid' => $usid
));
// Creating a PHP array
$gyvuliu_array = array();
// Fetching through the array and inserting query results using $num variable ((int) makes sure a value is an integer)
while ($stmt1->fetch(PDO::FETCH_ASSOC)) {
$gyvuliu_array[] = (int)$num;
}
// Encoding PHP array so we will be able to use it in the JS code
$array_encode = json_encode($gyvuliu_array);
?>
<script>
var gyvuliai_fermoje = <?php echo $array_encode; ?>;
for (var i = 0; i < gyvuliai_fermoje.length; i++) {
// Stuff you would like to do with this array, access elements using gyvuliai_fermoje[i]
}
</script>
I hope it will help you to understand how to use a PHP array in the JS code in PDO :)

Converting javascript array to ViewBag or ViewData to acces data from controller

I have a dynamic table in my form on Save button click I am accessing the whole table and storing it to array using javascript. FOllowing is the javascript
function SaveData() {
var MedicineName = new Array();
var BatchNo = new Array();
var ExpiryDate = new Array();
var Qty = new Array();
var FreeQty = new Array();
var PurRate = new Array();
var Mrp = new Array();
var SellRate = new Array();
var Unit = new Array();
var Amount = new Array();
var DiscPer = new Array();
var DiscAmt = new Array();
var GrossAmt = new Array();
var VatPer = new Array();
var VatAmt = new Array();
var AddVatPer = new Array();
var AddVatAmt = new Array();
var NetAmt = new Array();
$("table#tbl1 tr").each(function (row, tr) {
MedicineName[row] = $(tr).find('td:eq(1)').text()
BatchNo[row] = $(tr).find('td:eq(2)').text()
ExpiryDate[row] = $(tr).find('td:eq(3)').text()
Qty[row] = $(tr).find('td:eq(4)').text()
FreeQty[row] = $(tr).find('td:eq(5)').text()
PurRate[row] = $(tr).find('td:eq(6)').text()
Mrp[row] = $(tr).find('td:eq(7)').text()
SellRate[row] = $(tr).find('td:eq(8)').text()
Unit[row] = $(tr).find('td:eq(9)').text()
Amount[row] = $(tr).find('td:eq(10)').text()
DiscPer[row] = $(tr).find('td:eq(11)').text()
DiscAmt[row] = $(tr).find('td:eq(12)').text()
GrossAmt[row] = $(tr).find('td:eq(13)').text()
VatPer[row] = $(tr).find('td:eq(14)').text()
VatAmt[row] = $(tr).find('td:eq(15)').text()
AddVatPer[row] = $(tr).find('td:eq(16)').text()
AddVatAmt[row] = $(tr).find('td:eq(17)').text()
NetAmt[row] = $(tr).find('td:eq(18)').text()
TableData.shift();
MedicineName.shift();
BatchNo.shift();
ExpiryDate.shift();
Qty.shift();
FreeQty.shift();
PurRate.shift();
Mrp.shift();
SellRate.shift();
Unit.shift();
Amount.shift();
DiscPer.shift();
DiscAmt.shift();
GrossAmt.shift();
VatPer.shift();
VatAmt.shift();
AddVatPer.shift();
AddVatAmt.shift();
NetAmt.shift();
}
Now I want to store it in ViewBag or ViewData or any more efficient way from this 2 to controller.
Note: I dont only have to save value of table there are couple other fields I am storing and all things are inter related so I want to get done this thing at once not like calling some other function first to save this data and other function for other data of the same form

PHP JSON variable in javascript

I am generating a JSON "text" using php and want to include that in a javascript in the same file.
I think I am having problem understanding how java deals with JSON as text vs as an Object.
Note: I am going to change mysql to mysqli soon, just want to get this thing working first.
Here's my script:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Knox QA tickets status</title>
</head>
<body>
<script src="am/amcharts/amcharts.js" type="text/javascript"></script>
<script src="am/amcharts/serial.js" type="text/javascript"></script>
<?php
//$subm = "8";
// This is being loaded from a selection html script
$subm = $_POST["submoduleID"];
if(!isset($_POST["submoduleID"]) )
{
// set it to the default container if it's not set.
$subm = "8";
}
// Connect to MySQL
$link = mysql_connect( 'localhost', 'root', 'secret' );
if ( !$link ) {
die( 'Could not connect: ' . mysql_error() );
}
// Select the data base
$db = mysql_select_db( 'xqa_status', $link );
if ( !$db ) {
die ( 'Error selecting database \'test\' : ' . mysql_error() );
}
// Fetch the data
$query = ("select date, tested, passed from test_status where xqa_id=" . $subm . " order by test_status_id limit 10");
$result = mysql_query( $query );
// Make a josn formatted output
$rows = array();
while ( $r = mysql_fetch_assoc($result)) {
$rows[] = $r;
}
$chartData_json = json_encode($rows);
print $chartData_json;
mysql_close($link);
?>
<!-- Custom Function
<script>
AmCharts.loadJSON = function(file) {
// create the request
if (window.XMLHttpRequest) {
// IE7+, Firefox, Chrome, Opera, Safari
var request = new XMLHttpRequest();
} else {
// code for IE6, IE5
var request = new ActiveXObject('Microsoft.XMLHTTP');
}
request.open('GET', file, false);
request.send();
// parse adn return the output
return eval(request.responseText);
};
</script> -->
<!-- chart container -->
<div id="chartdiv" style="width: 600px; height: 300px;"></div>
<!-- the chart code -->
<script>
var chart;
var chartData1 = "<?php echo $chartData_json; ?>";
var myObject = JSON.parse(chartData1, reviver);
// create chart
AmCharts.ready(function() {
// load the data
// SERIAL CHART
chart = new AmCharts.AmSerialChart();
chart.pathToImages = "am/amcharts/images/";
chart.dataProvider = myObject;
chart.categoryField = "date";
chart.dataDateFormat = "YYYY-MM-DD";
// GRAPHS
var graph1 = new AmCharts.AmGraph();
graph1.type = "smoothedLine";
graph1.title = "Tested";
graph1.valueField = "tested";
graph1.bullet = "round";
graph1.bulletSize = 5;
graph1.bulletBorderColor = "#FFFFFF";
graph1.bulletBorderThickness = 2;
graph1.lineThickness = 2;
graph1.lineAlpha = 0.5;
chart.addGraph(graph1);
var graph2 = new AmCharts.AmGraph();
graph2.type = "smoothedLine";
graph2.title = "Passed";
graph2.valueField = "passed";
graph2.bullet = "round";
graph2.bulletSize = 5;
graph2.bulletBorderColor = "#FFFFFF";
graph2.bulletBorderThickness = 2;
graph2.lineThickness = 2;
graph2.lineAlpha = 0.5;
chart.addGraph(graph2);
// CATEGORY AXIS
chart.categoryAxis.parseDates = true;
chart.categoryAxis.autoGridCount = false;
chart.categoryAxis.gridCout = chartData.length;
chart.categoryAxis.gridPosition = "start";
chart.categoryAxis.labelRotation = 90;
// LEGEND
var legend = new AmCharts.AmLegend();
chart.addLegend(legend);
// CURSOR
var chartCursor = new AmCharts.ChartCursor();
chartCursor.cursorAlpha = 0;
chartCursor.cursorPosition = "mouse";
chartCursor.categoryBalloonDateFormat = "YYYY-MM-DD";
chart.addChartCursor(chartCursor);
// SCROLLBAR
var chartScrollbar = new AmCharts.ChartScrollbar();
chart.addChartScrollbar(chartScrollbar);
// 3D
// chart.angle = 30;
// chart.depth3D = 15;
// WRITE
chart.write("chartdiv");
});
</script>
</body>
</html>
A sample of the json output is this:
[{"date":"2014-01-09","tested":"12","passed":"32"},{"date":"2014-01-10","tested":"12","passed":"34"},{"date":"2014-01-11","tested":"22","passed":"34"},{"date":"2014-01-12","tested":"22","passed":"34"},{"date":"2014-01-13","tested":"40","passed":"34"},{"date":"2014-01-14","tested":"40","passed":"34"},{"date":"2014-01-15","tested":"40","passed":"34"}]
You need to assign the output of your PHP into a Javascript variable:
<script>
var json_data=<?php
...
?>;
// Do stuff with json_data
</script>
Then json_data will be an array or objects in Javascript (it's not JSON anymore since the JSON will be parsed as an array literal, not a string). That is most likely what you want, since then you can work with the array, like json_data[0].data.

PHP looped output of mySQL table is missing one row

Summary of problem: I have a mysql table with some data, I use some phpcode to display the data to an html page, to setup JavaScript variables before a page loads. The loop seems to work fine with one exception, the first row of the table gets dropped or doesnt show. I cant figure out why, is there a small bit of logic Im missing?
I have a mySQL table here:
http://gyazo.com/ac75247b1a3f11f59721f03ff9c80d08
and some php code to display it here:
//...
$sql = "SELECT * FROM ".TABLE_CALCULATOR." WHERE calculation_status = 'A'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
$num_rows = mysql_num_rows($result);
if(count($num_rows) > 0 ){
while ($row = mysql_fetch_assoc($result)) {
$calculator_data[] = $row;
}
}else{
// Send Notication to admin Calculator not set
}
//...
<?php
if(!empty($calculator_data)){
foreach($calculator_data as $k => $v ){
if($v['name_value'] == 'perWinPriceMatrix'){
$per_win_matrinx = explode(",", $v['calculation_values'] );
$per_win_matrinx_final = array_chunk($per_win_matrinx, 5, true);
foreach($per_win_matrinx_final as $key => $values ){
$var[$key] = $key.':['.implode(',',$values).']';
}
?> var <?php echo $v['name_value'] ;?> = <?php echo "{".implode(",", $var)."}";?>;<?php echo "\n";
}else{
?> var <?php echo $v['name_value'] ;?> = [<?php echo $v['calculation_values'] ;?>];<?php echo "\n";
}
}
}
?>
this is the output:
var tax_bronze2 = [30,20,20,5,0];
var tax_bronze3 = [30,20,20,5,0];
var tax_bronze4 = [25,20,20,5,0];
var tax_bronze5 = [25,20,20,5,0];
var tax_silver1 = [35,30,30,5,0];
var tax_silver2 = [30,20,20,5,0];
var tax_silver3 = [30,20,20,5,0];
var tax_silver4 = [30,20,20,5,0];
var tax_silver5 = [30,20,20,5,0];
var tax_gold1 = [70,50,30,10,0];
var tax_gold2 = [60,40,20,8,0];
var tax_gold3 = [60,40,20,8,0];
var tax_gold4 = [60,40,20,8,0];
var tax_gold5 = [60,40,20,8,0];
var tax_platinum1 = [100,75,40,10,0];
var tax_platinum2 = [80,65,40,10,0];
var tax_platinum3 = [80,65,40,10,0];
var tax_platinum4 = [80,65,40,10,0];
var tax_platinum5 = [80,65,40,10,0];
var tax_diamond1 = [0,0,0,0,0];
var tax_diamond2 = [120,85,50,20,0];
var tax_diamond3 = [120,85,50,20,0];
var tax_diamond4 = [120,85,50,20,0];
var tax_diamond5 = [120,85,50,20,0];
var perWinPriceMatrix = {0:[4,4,4,4.5,4.75],1:[5,5.3,5.7,6.2,6.2],2:[7.8,8.6,9.7,10.8,11.8],3:[13,15,17,18,18],4:[19,21,25,30,40]};
var price_matrix = [19,20,20,20,32,24,24,24,24,42,46,51,53,56,60,60,65,74,79,140,186,214,242,298];
var provisionalPrice = [60,80,9.25,13,1.3,0.75];
question: Why is output missing a row?
delete $row = mysql_fetch_array($result); this line fetch row #1

Categories

Resources