PHP array to Javascript in a loop - javascript

First of all I have the following MySQL table name as store_items :
id ref store item qty sell
1 2 m1 001 1 12.00
2 2 m1 002 3 12.00
3 3 m3 004 4 5.00
4 3 m3 003 8 10.00
And starting with a simple PHP code to convert the above rows to an array
<?php
$query = "SELECT * FROM store_items ORDER by store Asc";
$result = mysql_query($query);
while ($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
//This is for moving PHP array to JS array ? Not sure if it is correct
$js_arr = json_encode($data);
?>
Now I have been looking for a way rather than displaying it as a table , so I want to place those results inside an Excel look alike, so I found this plugin called : Javascript Handsontable
Moving on , after placing the style sheets and the scripts :
<script src="http://localhost/handsontable-master/dist/handsontable.full.js"></script>
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/dist/handsontable.full.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<link rel="stylesheet" media="screen" href="http://localhost/handsontable-master/demo/css/samples.css">
<style type="text/css">
body {background: white; margin: auto;}
h2 {margin: 20px 0;}
</style>
<div id="example" class="handsontable htColumnHeaders"></div>
So the Problem arises over here :
<script>
var array_code = '<?php echo $js_arr; ?>';
//Alerting result to make sure its correct
alert(array_code);
$(document).ready(function () {
//Not sure how to display the results here ???
var
data =
[
array_code
],
container = document.getElementById('example'),
hot;
hot = new Handsontable(container, {
data: data,
minSpareRows: 1,
colHeaders: true,
contextMenu: true
});
function bindDumpButton() {
Handsontable.Dom.addEvent(document.body, 'click', function (e) {
var element = e.target || e.srcElement;
if (element.nodeName == "BUTTON" && element.name == 'dump') {
var name = element.getAttribute('data-dump');
var instance = element.getAttribute('data-instance');
var hot = window[instance];
console.log('data of ' + name, hot.getData());
}
});
}
bindDumpButton();
});
But I can't achieve the correct display; what I'm aiming for is something like this:
But the above picture is shown correct when var data array values are like this
var
data = [
['1', '2', 'm1', '001', '1', '12.00'],
['2', '2', 'm1', '002', '3', '12.00'],
['3', '3', 'm3', '004', '4', '5.00'],
],
How can I place the PHP array values inside JS array correctly?
Any suggestions will be appreciated.

Maybe I'm missing something (in which case comment and i'll edit my answer), but I think you just need to replace:
while ($row = mysql_fetch_assoc($result)){
$data[] = $row;
}
with:
while ($row = mysql_fetch_row($result)){
$data[] = $row;
}
and your "data" should be exactly array_code

You don't need to use $js_arr = json_encode($data); for displaying the data in the HTML table since it would produce JSON formatted data and if you're not going to manipulate the table using JavaScript, you can avoid doing this way. Just add the following HTML code and style it however you want:
<table>
<thead>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
<th>E</th>
<th>F</th>
</thead>
<tbody>
<?php if(!empty($data)): ?>
<?php foreach($data as $row): ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['ref'] ?></td>
<td><?= $row['store'] ?></td>
<td><?= $row['item'] ?></td>
<td><?= $row['qty'] ?></td>
<td><?= $row['sell'] ?></td>
</tr>
<?php endforeach; ?>
<?php endif; ?>
</tbody>
</table>

Related

count duplicate data in mysql

Is there a way to count the duplicate data from mysql and
display it to a bar chart, Im trying to make a attendance report
using morris bar chart.
here my sample code:
<html >
<head>
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.css">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/raphael/2.1.0/raphael-min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/morris.js/0.5.1/morris.min.js"></script>
</head>
<body>
<div id="chart"></div>
</body>
</html>
here is my php code:
<?php
$connect = mysqli_connect("localhost", "root", "", "sa");
$query = "SELECT year, count(*) as course FROM test group by year,course order by year ASC ";
$result = mysqli_query($connect, $query);
$chart_data = '';
while($row = mysqli_fetch_array($result))
{
$chart_data .= "{ year:'".$row["year"]."', course:".$row["course"]."}, ";
}
$chart_data = substr($chart_data, 0, -2);
?>
and this is my javascript:
<script>
Morris.Bar({
element : 'chart',
data:[<?php echo $chart_data; ?>],
xkey:'year',
ykeys:['course','course','course','course','course'],
labels:['BSIT','BSHRM','BSCS','BSTM','ABCOMM'],
hideHover:'auto',
xLabelAngle: '60',
verticalGrid: true,
resize:true,
barColors: ['red','blue','green','yellow','black'],
gridTextSize: 12
});
</script>
this is my database:
UPDATED: and this is my output so far:
as you can see in my output all courses have same value for example
the two 2018-07-12 the output should be based on my database is for BSIT = 3
the rest is zero value same with the other 2018-07-12 the output should be BSHRM =1 and the rest is zero value, is there a way to achieve that?, Hope you can help me.
You have two problems with your query:
First, the alias COUNT(*) AS course reuses the column name as the alias. You need to give it a different name.
Second, you left course out of the grouping, so you're combining the counts of all courses in your results.
It should be:
$query = "SELECT year , course , count(*) as count FROM test group by year, course order by year ASC ";
Each course will then be in a different row of the results, you'll need to regroup when you process the results.
You also shouldn't create JSON by concatenating strings. Put the results in an array and use json_encode().
$results = array();
while ($row = mysqli_fetch_assoc($result)) {
$results[$row['year']]['year'] = $row['year'];
$results[$row['year']][$row['course']] = $row['count'];
}
$chart_data = json_encode(array_values($results));
This method uses the course names as the keys in the JSON, not course1, course2, etc. So you need to change
ykeys:['course','course','course','course','course'],
to:
ykeys:['BSIT','BSHRM','BSCS','BSTM','ABCOMM'],
The JSON in $chart_data already includes the square brackets around the array, so you don't need to add it around the echo. Use:
data: <?php echo $chart_data; ?>,

Google Charts Dynamic Arrays PHP Without SQL

I'm asking this question because all the answers I could find for similar problems were using MySQL whereas I'm not, just a JSON API to get the data, which I then put into arrays that I want to display as a Google graph. All I know is that I have to somehow format the arrays properly in order to get them to display but I have no idea how to do it in my case. I would just like to have a simple pie chart, based on the arrays below. So far I'm getting a blank space on the site. I tried something with Json_encode before but it didn't work so I decided to leave it as it is and come here instead. Here are the arrays after I do print_r:
Array 'name'-
Array ( [0] => Facebook Inc [1] => Alphabet Class A [2] => Apple Inc [3] => Ford Motor Company [4] => Adv Micro Devices [5] => Morgan Stanley [6] => Berkshire Hath Hld B [7] => JP Morgan Chase & Co )
Array 'sumOf'-
Array ( [0] => 5811.63 [1] => 116135.97 [2] => 1564.1 [3] => 1053 [4] => 113.1 [5] => 521.4 [6] => 1960.2 [7] => 1100.4 )
Code:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable($name, $sumOf);
var options = {
title: 'Portfolio Allocation'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
How arrays are made:
$name = [];
$lastprice = [];
$y = 0;
$z = '';
$key = "";
// Retreiving information from database
$memberid = $_SESSION['memberID'];
$sql = "SELECT * FROM portfolio WHERE memberID = $memberid";
$result = mysqli_query($conn, $sql);
// Check if databse is empty
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$sym[$y] = $row["stocks_symbol"];
$pri[$y] = $row["price"];
$vol[$y] = $row["quantity"];
$id[$y] = $row["memberid"];
$y += 1;
}
}
// If database empty
else
{
echo "Portfolio Empty";
die();
}
mysqli_close($conn);
// Adding all stock names in one variable to enable API call
for($a=0;$a<$y;$a++)
{
$z = $z.$sym[$a].',';
}
$z = rtrim($z,",");
// API call
$contents = file_get_contents("http://marketdata.websol.barchart.com/getQuote.json?key=$key&symbols=$z&mode=R");
$contents = json_decode($contents, true);
// Check successfull API call
if($contents["status"]["code"] == 200)
{
foreach($contents['results'] as $result)
{
array_push($name,$result['name']);
array_push($lastprice,$result['lastPrice']);
}
}
// If API call unsuccessful
else
{
echo "Error retreiving data. Please try again later.";
die();
}
?>
<!-- Generating Output in tabular format -->
<table id= test class='table table-responsive'>
<tr class='head warning'>
<th>Name</th>
<th>Last Price</th>
<th>Price Bought</th>
<th>Quantity</th>
<th>Change Per Stock</th>
<th>Profit/Loss</th>
<th>Market Value</th>
<th>Amount Invested</th>
</tr>
<?php
$profitOrLossSum = 0;
$dividendRateSum = 0;
$startEqSum = 0;
$sumOf = array();
for($x=0;$x<$y;$x++)
{?>
<tr>
<td class="input"><?php echo $name[$x]; ?></td>
<td class="input"><?php echo $lastprice[$x]; ?></td>
<td class="input"><?php echo $pri[$x]; ?></td>
<td class="input"><?php echo $vol[$x]; ?></td>
<td class="input"><?php
if($pri[$x] > $lastprice[$x])
{
echo $lastprice[$x]-$pri[$x];
}
else if($pri[$x] < $lastprice[$x])
{
echo $lastprice[$x]-$pri[$x];
}
else
echo '0';
?></td>
<td class="input"><?php
$profitOrLoss = ($lastprice[$x]-$pri[$x]) * $vol[$x];
$profitOrLossSum += $profitOrLoss;
echo $profitOrLoss;
?></td>
<td><?php
$firstno1 = floatval($vol[$x]);
$secondno1 = floatval($lastprice[$x]);
$sumOf[] = $firstno1 * $secondno1;
$sum1 = $firstno1 * $secondno1;
print ($sum1);
?></td>
<td class="input">
<?php
$starteq = $pri[$x] * $vol[$x];
$startEqSum += $starteq;
echo $starteq;
?>
</td>
</tr>
<?php
}
$arr = array('profitOrLossSum' => $profitOrLossSum, 'dividendRateSum' => $dividendRateSum);
$arr1 = array('startEqSum' => $startEqSum);
print_r ($name);
print_r ($sumOf);
echo json_encode($name);
echo json_encode($sumOf);
?>
Here is the working Example of your code you were very close though. Actually, you have to pass only one single parameter as a multidimensional array to arrayToDataTable(); you have to json_encode and JSON_parse your array as well
check https://developers.google.com/chart/interactive/docs/gallery/piechart
No worries its working copy and paste it and you are good to go.
<?php
$name = ['Facebook Inc', 'Alphabet Class A', 'Apple Inc', 'Ford Motor Company', 'Adv Micro Devices', 'Morgan Stanley', 'Berkshire Hath Hld B', 'P Morgan Chase & Co'];
$sumOf = [5811.63, 116135.97, 1564.1, 1053, 113.1, 521.4, 1960.2, 1100.4];
?>
<html>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages': ['corechart']});
google.charts.setOnLoadCallback(drawChart);
var name = <?= json_encode($name) ?>;
var sumOf = <?= json_encode($sumOf) ?>;
var array = name.split(",");
newArr = [['Name', 'Amount']];
array.forEach(function (v, i) {
newArr.push([v, sumOf[i]]);
});
function drawChart() {
var data = google.visualization.arrayToDataTable(newArr);
var options = {
title: 'Portfolio Allocation'
};
var chart = new google.visualization.PieChart(document.getElementById('piechart'));
chart.draw(data, options);
}
</script>
<body>
<div id="piechart" style="width: 900px; height: 500px;"></div>
</body>
</html>
array_combine was needed to join the two arrays together and then inside of
'function drawChart' a simple foreach loop was required, like this:
<?php
foreach ($array as $name => $allocation):
echo "['$name', $allocation]";
echo ($allocation != end($array)) ? ',' : '';
endforeach;
?>

How to Pass every Php value to javascript URL (only showing 1 same row record)

Need help on below coding.
However I got few running no, when I press edit button it only show running no '1', other running no like 2 or 3 also showing running no 1 when i press edit on the row 2 and row 3.
I got a problem in index.php file:
<html>
<?php
$rb = $connect->Execute("SELECT * FROM IT_Dept.dbo.testingHeader A LEFT JOIN IT_Dept.dbo.testingDetail B
ON A.invoiceno=B.invoiceno_dt
WHERE A.invoiceno = '".$search."'");
}
$invoiceno = $rb->Fields("invoiceno");
$company = $rb->Fields("company");
$custname = $rb->Fields("custname");
$newadd=str_replace("<br />","\n",$custadd);
//table details
?>
<body>
<?php
echo "<form id= 'form2' method='post'><table id='tabledesc' border=1>
<tr>
<th>Description </th>
<th>Qty</th>
<th >Unit Price(Before GST)</th>
<th>Total(Before GST)</th>
<th >*Total GST</th>
<th >Amount(RM)</th>
<th >Tax input/output</th>
<th >Debit Acc</th>
</tr>";
while(!$rb->EOF) {
$description = $rb->Fields("description");
$invoiceno_dt = $rb->Fields("invoiceno_dt");
$runningno = $rb->Fields("runningno");
$qty = $rb->Fields("qty");
$unitprice = $rb->Fields("unitprice");
$totalb4gst = $rb->Fields("totalb4gst");
$gst = $rb->Fields("gst");
$amount = $rb->Fields("amount");
>Fields("creditacc");
$description = $description->value;
$invoiceno_dt = $invoiceno_dt->value;
$runningno = $runningno->value;
$qty = $qty->value;
$unitprice = $unitprice->value;
$totalb4gst = $totalb4gst->value;
$gst = $gst->value;
$amount = $amount->value;
echo "<tr><td>".$description."</td>";
echo "<td>".$qty."</td>";
echo "<td>".$unitprice."</td>";
echo "<td>".$totalb4gst."</td>";
echo "<td>".$gst."</td>";
echo "<td>".$amount."</td>";
echo "<input type='hidden' name = 'runningno' id='runningno' value = ' $runningno ' >";
echo "<td><button onclick='openedit()'>Edit</button></td>";
invoiceno_dt=".$invoiceno_dt."&runningno=".$runningno."'>Edit</a></td>";
invoiceno_dt=".$invoiceno_dt."&runningno=".$runningno."'>x</a></td><tr>";
echo "<td><button onclick='opendelete()'>Delete</button></td>";
$rb->MoveNext();
}
?>
</table></form></body>
<script type="text/javascript">
var popup;
function openedit() {
var myinvoice = document.getElementById("invoiceno").value;
var no = <?php echo $runningno; ?>;
alert(no);
popup = window.open("edit.php?invoiceno="+myinvoice+'&runningno='+no, "Popup", "width=500,height=600");
popup.focus();
}
popup.focus();
}
</script>
<?php
$rb->close;
$connect->close;
?>
You could add the running number to the page for example by doing this:
<script type="text/javascript">
var no = <?php echo $runningNo; ?>;
</script>
Try this.
echo "<td><button onclick=\"openedit('{$runningno}')\">Edit</button></td>";
Apart from that, you better to remove the spaces in value attribute in input field.
echo "<input type='hidden' name='runningno' id='runningno' value ='$runningno' />";
Use as suggested for template files
<html>
<!-- HTML code is here -->
<input type='hidden' name = 'runningno' id='runningno' value = '<?php print $runningno; ?>'></input>
<!-- Some other html -->
<?php
//your php code here
?>
<!-- HTML again -->
</html>
Same for js inside html
<script type="text/javascript">
var testJsValue = "<?php print $ValueFromPHP; ?>";
</script>
Try this
echo '<td><button onclick="openedit(\''.$runningno.'\')">Edit</button></td>';
I think this code will be work properly.

slide show using javascript using php variable

I am trying to get member photos from my sql and show as a slide. i am trying this with DHTML slideshow script- © Dynamic Drive DHTML code library (www.dynamicdrive.com) check the basic code here basic code
now i change the code to get the image url from mysql using php
my code :
Here is the html and script code.
<html>
<head>
<script type="text/javascript">
/***********************************************
* DHTML slideshow script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice must stay intact for legal use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
var photos = new Array()
<?php
$mid=$_POST['mid'];
//echo $mid;
$mid=$_POST['mid'];
require_once("datacon.php");
$result = $data->query("SELECT * FROM tempregist where id= $mid ");
$row = mysqli_fetch_array($result) or die(mysqli_error());
$folde= "uploads/thumb/";
$folder=utf8_encode($folde);
//echo $folder;
$mid1 =$row['mid'];
require_once("datacon.php");
$result = $data->query("SELECT image_name FROM tbl_images where mid= '$mid1' ");
$phparray = array();
$count = mysqli_num_rows($result);
if($count>=1)
{
while($crow = mysqli_fetch_array($result))
{
$i=0;
$phparray[$i] = $folder. $crow['image_name'];
$i++;
?>
photos<?php echo"[".$i."]" ;?> = <?php echo '"'. implode( $phparray) . '"'."\n" ;
} }
?>
var photoslink = new array
var x
x =<?php echo json_encode($count) ?>;
var which=0
/
//Specify whether images should be linked or not (1=linked)
var linkornot=0
Set corresponding URLs for above images. Define ONLY if variable linkornot equals "1"
photoslink[0]=""
photoslink[1]=""
photoslink[2]=""
//do NOT edit pass this line
var preloadedimages=new Array()
for (i=0;i<photos.length;i++){
preloadedimages[i]=new Image()
preloadedimages[i].src=photos[i]
}
function applyeffect(){
if (document.all && photoslider.filters){
photoslider.filters.revealTrans.Transition=Math.floor(Math.random()*23)
photoslider.filters.revealTrans.stop()
photoslider.filters.revealTrans.apply()
}
}
function playeffect(){
if (document.all && photoslider.filters)
photoslider.filters.revealTrans.play()
}
function keeptrack(){
window.status="Image "+(which+1)+" of "+photos.length
}
function backward(){
if (which>0){
which--
applyeffect()
document.images.photoslider.src=photos[which]
playeffect()
keeptrack()
}
}
function forward(){
if (which<photos.length-1){
which++
applyeffect()
document.images.photoslider.src=photos[which]
playeffect()
keeptrack()
}
}
function transport(){
window.location=photoslink[which]
}
</script>
</head>
<body>
<div align="center">
<img src="images/logo.jpg" border = "2" align="center" alt="no logo">
</div>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100%" colspan="2" height="22"><center>
<script>
if (linkornot==1)
document.write('<a href="javascript:transport()">')
document.write('<img src="'+photos[0]+'" name="photoslider" style="filter:revealTrans(duration=2,transition=23)" border=0>')
if (linkornot==1)
document.write('</a>')
</script>
</center></td>
</tr>
<tr>
<td width="50%" height="21"><p align="left">Previous Slide</td>
<td width="50%" height="21"><p align="right">Next Slide</td>
</tr>
</table>
<p align="center"><font face="Arial" size="-2">Free DHTML scripts provided by<br>
Dynamic Drive</font></p>
</body>
</html>
Now i am getting out put as follows
var photos = new Array()
photos[0] = "uploads/thumb/220816_1412135472.jpeg"
photos[0] = "uploads/thumb/312840_1412135511.jpeg"
photos[0] = "uploads/thumb/589453_1412135511.jpeg"
photos[0] = "uploads/thumb/467341_1412135630.jpeg"
photos[0] = "uploads/thumb/800658_1412135790.jpeg"
photos[0] = "uploads/thumb/366793_1412135826.jpeg"
But i need the out put like this
photos[0] = "uploads/thumb/220816_1412135472.jpeg"
photos[1] = "uploads/thumb/312840_1412135511.jpeg"
photos[2] = "uploads/thumb/589453_1412135511.jpeg"
photos[3] = "uploads/thumb/467341_1412135630.jpeg"
photos[4] = "uploads/thumb/800658_1412135790.jpeg"
photos[5] = "uploads/thumb/366793_1412135826.jpeg"
i tried so much. please any one help.
while($crow = mysqli_fetch_array($result))
{
$i=0;
You're resetting $i in your loop
$result = $data->query("SELECT image_name FROM tbl_images where mid= '$mid1' ");
{
$count = mysqli_num_rows($result);
if($count>=1)
{
$i=0;
while($crow = mysqli_fetch_array($result))
{
$phparray[$i] = $folder. $crow['image_name'];
echo $i. "\n";
$i++;
}
}
use $i=0 initialization outside while
finally i found it with help of Hammerstein and Dhanush Bala. i mingled two persons suggestion i got it here is the answer
$phparray = array();
$count = mysqli_num_rows($result);
if($count>=1)
{
$b=0;
while($crow = mysqli_fetch_array($result))
{
$i=0;
$phparray[$i] = $folder. $crow['image_name'];
$i++;
$b++;
?>
photos<?php echo"[".$b."]" ;?> = <?php echo '"'. implode( $phparray) . '"'."\n" ;
} }
now the out put is:
photos[1] = "uploads/thumb/220816_1412135472.jpeg"
photos[2] = "uploads/thumb/312840_1412135511.jpeg"
photos[3] = "uploads/thumb/589453_1412135511.jpeg"
photos[4] = "uploads/thumb/467341_1412135630.jpeg"
photos[5] = "uploads/thumb/800658_1412135790.jpeg"
photos[6] = "uploads/thumb/366793_1412135826.jpeg"
thanks Hammerstein and Dhanush Bala

pass a php array to javascript for a horizontal on hover pop up submenu

I am currently working on a revamp of an outdated site. I have updated the html, php and converted it from a mysql database to sql database. All that is good and fine. My area of knowledge is in databases, php, sql, and fair with the html. One problem is that the site is using an old javascript project/library called HM_LOADER.js which uses a hard coded array for the sub menu items HM_ARRAY.js. The function that creates main menu, and begins the use of the javascript is this:
function printOrderRequestOptions()
{
?>
<SCRIPT LANGUAGE="JavaScript1.2"
SRC="HM_Loader.js"
TYPE='text/javascript'></SCRIPT>
<table width="142" height=450 border="0" cellpadding="0" cellspacing="0" bgcolor="500b4c">
<tr>
<td valign="middle">
<a href="order.php"
onMouseOver="image1.src='/images/header/finance_on.gif';popUp('elMenu1',event)"
onMouseOut="image1.src='/images/header/finance_off.gif';popDown('elMenu1')">
<img name="image1" src="/images/header/finance_off.gif" border=0></a>
</td>
</tr>
<tr>
<td valign="middle">
<a href="order.php"
onMouseOver="image2.src='/images/header/salesseries_on.gif';popUp('elMenu2',event)"
onMouseOut="image2.src='/images/header/salesseries_off.gif';popDown('elMenu2')">
<img name="image2" src="/images/header/salesseries_off.gif" border=0></a>
</td>
</tr>
<tr>
<td valign="middle">
<a href="order.php"
onMouseOver="image3.src='/images/header/dealerservices_on.gif';popUp('elMenu3',event)"
onMouseOut="image3.src='/images/header/dealerservices_off.gif';popDown('elMenu3')">
<img name="image3" src="/images/header/dealerservices_off.gif" border=0></a>
</td>
</tr>
</table>
?>
}
which in turn uses the hm_loader, that in turn uses the HM_array file that looks like this:
HM_Array1 = [
[150,
142, // left_position
145, // top_position
],
["<b>Finance & Insurance</b>","/order_form.php?num=1&firstTime=1",1,0,0],
["<b>Legal Awareness</b>","/order_form.php?num=2&firstTime=1",1,0,0]
]
HM_Array2 = [
[180,
142,
260,
],
["<b>Sales Strength I</b>","/order_form.php?num=24&firstTime=1",1,0,0],
["<b>Sales Strength II</b>","/order_form.php?num=25&firstTime=1",1,0,0],
//["<b>Sales Strength II Handouts</b>","/order_form.php?num=26&firstTime=1",1,0,0],
["<b>Communispond</b>","/order_form.php?num=36&firstTime=1",1,0,0],
["<b>PSS</b>","/order_form.php?num=35&firstTime=1",1,0,0]
]
HM_Array3 = [...
I need to make this dynamic based on queries from my database. Under my work guidelines I am allowed minimal restructuring of the site and files therein. So, basically they to keep the system intact as is, but make these sub menu items dynamic. I am on my third day of beating my head against the wall. I know how to create my data structure in php and then json encode it, but how can I use that in this existing code system? If more information is needed please let me know. Today was my deadline to show something, and I am still stuck on 'Where do I start'...
I'm not entirely sure what your question is, but maybe this will get you started.
I suspect you are stuck somewhere between getting the values from the database and trying to output them to javascript. json_encode() is the answer here, you know that. I'm not sure where you are struggling exactly.
This will help with that, just throw it in an example.php and run it. It doesn't actually use the javascript, it just shows you the output (copy/paste to the console if you want to try it):
Here is a screenshot of the output: http://radleygh.com/images/chrome_2014-022-15-13-12-16.png
<?php
// Here is a single base object (HM_Array1), we'll add sub items separately
$array = array(
'position' => array(
150, // Mystery!
142, // Left
145, // Top
),
'items' => array(),
);
// Add your items separately, preferably in a loop. This isn't a loop, that would be superflous.
$array['items'][] = array(
'title' => '<b>Finance & Insurance</b>',
'slug' => '/order_form.php?num=1&firstTime=1',
'x' => 1,
'y' => 0,
'z' => 0,
);
$array['items'][] = array(
'title' => '<b>Legal Awareness</b>',
'slug' => '/order_form.php?num=2&firstTime=1',
'x' => 1,
'y' => 0,
'z' => 0,
);
// You'll want to see how this works, so here's some debuggery:
echo '<h3>Preview of your object in PHP:</h3>';
echo '<pre>';
echo htmlspecialchars( print_r($array, true) );
echo '</pre>';
echo '<hr />';
echo '<h3>The javascript version:</h3>';
echo '<pre>';
ob_start();
?>
jQuery.parseJSON( '<?php echo json_encode( $array ); ?>' );
<?php
$html = ob_get_clean();
echo htmlspecialchars( print_r( $html, true) );
echo '</pre>';
The main part of this code is the jQuery.parseJSON line, which will produce an object version of the PHP array. You can then use that object to structure the HM_ArrayN arrays that you have provided using a function. Maybe you want to set this up with ajax, that's fine too, just parse the JSON after you perform the ajax query.
That javascript line of code will give you the following object:
Object {
position: array(
0: 150
1: 142
2: 145
)
items: array(
0: {
slug: "/order_form.php?num=1&firstTime=1"
title: "<b>Finance & Insurance</b>"
x: 1
y: 0
z: 0
}
1: {
slug: "/order_form.php?num=2&firstTime=1"
title: "<b>Legal Awareness</b>"
x: 1
y: 0
z: 0
}
}
You can then build a function which converts this well-formed array into the format required by the specifications. Example below:
var myObject = (the javascript code above);
var HM_Array1 = new Array();
HM_Array1[0] = myObject.position[0];
HM_Array1[1] = myObject.position[1];
HM_Array1[2] = myObject.position[2];
for( i in myObject.items ) {
var item = new Array();
item[0] = myObject.items[i].title;
item[1] = myObject.items[i].slug;
item[2] = myObject.items[i].x;
item[3] = myObject.items[i].y;
item[4] = myObject.items[i].z;
HM_Array.push( item );
}
console.log( HM_Array1 ); // Should look like your code.
In the originating page, order.php I make to function calls 'getClass()' and then pass that to printOrderRequestOptions($mainMenu). they are simple functions that looks like this:
function getClass()
{
$conn = connect();
$SQL = "select order_form_class_id, order_form_class_desc from order_form_class where order_form_class_status_id='100'";
$stmt = runsql($SQL, $res=NULL, $ERROR_MSG=NULL);
while($row=sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$id = $row['order_form_class_id'];
$desc= $row['order_form_class_desc'];
$classIds[] = array($id , $desc);
}
return $classIds;
}
function printOrderRequestOptions($mainMenu)
{
?>
<SCRIPT LANGUAGE="JavaScript1.2"
SRC="HM_Loader.js"
TYPE='text/javascript'></SCRIPT>
<style>
a {text-decoration:none;}
</style>
<table width="142" height=450 border="0" cellpadding="0" cellspacing="0" bgcolor="500b4c">
<tr><td><img name="image2" src="/images/header/generic_132X22.gif" border=0></a></td></tr>
<?
for ($i=0;$i<count($mainMenu);$i++)
{
?>
<tr>
<td align="center" valign="middle">
<a href="order.php"
onMouseOver="popUp('elMenu<?=$mainMenu[$i][0]?>',event)"
onMouseOut="popDown('elMenu<?=$mainMenu[$i][0]?>')">
<font color="white"><b><? echo $mainMenu[$i][1]; ?></b></font>
<img name="image<?=$i?>" src="/images/header/generic_132X22.gif" border=0></a>
</td>
</tr>
<?
}
?>
</table>
<?
}
From here HM_LOADER.js is called, which sets and configs the params, and then looks to HM_Arrays.js for the actual data. The arrays file was list of hard coded arrays, and I needed them to be dynamic. This solution is not the best, but it is what I had to do to make this work since I was a week past my initial demo presentation. The HM_Arrays.js has been renamed HM_Arrays.php and now looks like this:
<?php
include_once("functions/functions.php");
$arrayCount = getClass();
$subItems = subMenuItems();
//for ($x=0;$x<count($arrayCount);x++)
//{
$cnt = $arrayCount[0][0];
//echo $arrayCount;
print "HM_Array".$cnt." = [
[150,
142, // left_position
150, // top_position
],";
for ($i=0;$i<count($subItems);$i++)
{
if ($subItems[$i][0] == $cnt)
print "['<b>".$subItems[$i][1]."</b>','/order_form.php?num=".$subItems[$i][2]."&firstTime=1',1,0,0],";
}
print "],";
//}
$cnt = $arrayCount[1][0];
print "HM_Array".$cnt." = [
[325,
142, // left_position
250, // top_position
],";
for ($i=0;$i<count($subItems);$i++)
{
if ($subItems[$i][0] == $cnt)
print "['<b>".$subItems[$i][1]."</b>','/order_form.php?num=".$subItems[$i][2]."&firstTime=1',1,0,0],";
}
print "], ";
$cnt = $arrayCount[2][0];
print "HM_Array".$cnt." = [
[195,
142,
350,
],";
for ($i=0;$i<count($subItems);$i++)
{
if ($subItems[$i][0] == $cnt)
print "['<b>".$subItems[$i][1]."</b>','/order_form.php?num=".$subItems[$i][2]."&firstTime=1',1,0,0],";
}
print "], ";
$cnt = $arrayCount[3][0];
print "HM_Array".$cnt." = [
[240,
142,
450,
],";
for ($i=0;$i<count($subItems);$i++)
{
if ($subItems[$i][0] == $cnt)
print "['<b>".$subItems[$i][1]."</b>','/order_form.php?num=".$subItems[$i][2]."&firstTime=1',1,0,0],";
}
print "] ";
?>
I know it is a bit ugly, but I could not get a for loop to work. I was using the count of getClass() for my counter, but it would not work. Each sub-menu became blank once I tried. This is a working solution, is there anyone who can help get this working with more efficient code??? Thanks for any and all help!

Categories

Resources