Javascript not displaying what i would expect - javascript

I'm having a little trouble with Javascript/php/html. I have written this code below to display "GetM" if the time is > 480 seconds this seems to work great when there is just one instance of this. However, I have 14 blocks and any other blocks do not show their GetM values. Below is an image of what U mean by "blocks". The value for GetM on the first block is the percentage
<div id ="ZL01001Percent" class="BottomboxPercent">
<script type="text/javascript">
var time = <?php echo $machine1->data(); ?>;
var M = <?php echo $machine1->GetM(); ?>;
var P = M.toFixed(1);
if (time > 480) {
document.write(P * 100 + '%');
}
</script>
</div>
Any help would be much appreciated

I strongly recommend you create a JS Object representation of your data. If you create a PHP array, you can use json_encode to generate
var machines = <?PHP echo json_encode($myValues); ?>
which should result in
var machines = {
ZL01001: { time:500, M : 733},
ZL01002: { time:600, M : 556}
}
and then you can do
window.onload=function() {
for (var m in machines) {
var machine = machines[m];
document.getElementById(m+"Percent").innerHTML=machine.time>480?(machine.M.toFixed(1)*100)+"%":"";
}
}

Related

PHP file ouputs the javascript code itself and not running

I'm trying to create an Edit Modal. Provided that I have the html code for this, I write this javascript/jquery code:
<script type='text/javascript'>
$(function() {
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo " <script type'text/javascript'> alert('1');</script>";
$unitID = $r['unitID'];
$unitStatus = $r['unitStatus'];
$unitNumber = $r['unitNumber'];
$floorNumber = $r['floorCode'];
$unitType = $r['unitType'];
$t = $db->query("select floorLevel, floor_buildingID from tblFloors where floorLevel = '$floorNumber'");
while( $u = $t->fetch(PDO::FETCH_ASSOC)){
$floorLevel = $u['floorLevel'];
$floor_buildingID = $u['floor_buildingID'];
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = $unitType");
while($x = $w->fetch(PDO::FETCH_ASSOC)){
$unitTypeName = $x['unitTypeName'];
?>
$("#editModal<?php echo $unitID; ?>").click(function(){
$("#editUnitNumber").val("<?php echo $unitNumber;?>");
$("#editUnitType").val("<?php echo $unitType; ?>").material_select('update');
$("#editFloorNumber").val("<?php echo $floorNumber; ?>");
});
<?php }}}?>
});
The code above is used to write the data from the modal, but instead it output this:
$("#editModal5").click(function(){ $("#editUnitNumber").val("12002"); $("#editUnitType").val("4").material_select('update'); $("#editFloorNumber").val("12"); }); });
How do I solve that? What causes this?
Use json to pass data from php to javascript, instead of echoing everything out in one place. It may seem an overkill but it's readable, and is more beneficial on the long run.
The code below is not tested, but it should give you a general idea on how to approach these things. I did not include the second and third queries within the first while loop. You can nest the results from those queries in the $unit array and access the relevant data via additional loops in javascript.
Also, ideally you wouldn't just echo out the decoded array right after the php, a better solution would be to call a function in the footer, that would generate a script tag with all data that is used by javascript. Another approach is to use AJAX and get a json response only when you need it, then you would feed that same json to the loop.
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
$units = [];
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$unit = [
'unitID' => $r['unitID'],
'unitStatus' => $r['unitStatus'],
'unitNumber' => $r['unitNumber'],
'floorNumber' => $r['floorCode'],
'unitType' => $r['unitType']
];
$units[] = $unit;
}
$units_json = json_encode($units);
?>
<script type='text/javascript'>
$(function() {
var units = '<?php echo $units_json ?>';
var units_array = JSON.parse(units);
// do some validation here
for (var i = 0; i < units_array.length; i++) {
// do some validation here
$("#editModal" + units_array[i].unitID).click(function(){
$("#editUnitNumber").val(units_array[i].unitNumber);
$("#editUnitType").val(units_array[i].unitType).material_select('update');
$("#editFloorNumber").val(units_array[i].floorNumber);
});
};
});
</script>

how to extract a value from json file updated with ajax and using it as a php variable

json.php:
$array['value1'] = 100;
$array['value2'] = 500;
echo json_encode($array);
javascript:
$.getJSON('json.php', function(data) {
$('#value1').html(data.value1);
$('#value2').html(data.value2);
}
html:
<div id='value1'></div>
<div id='value2'></div>
the output would be:
100
500
question:
how would i have to change the javascript in order to use value1 and value2 as variables in a php script. for example:
script:
<?php if ($value1 < $value2) {
echo $value1." is smaller than ".$value2;
} else {
echo $value1." is bigger than ".$value2;
}
the output from my previous example would then be:
100 is smaller than 500
Thanks in advance!
You might check out this question in order to resolve your problem: Create variables from array keys in php
source code : https://ide.c9.io/ammaroff/stack
running example : https://stack-c9-ammaroff.c9.io/
js:
$.getJSON('json.php', function(data) {
$.post("server.php",data);
//$.post("server.php",{"value1":data.value1,"value2":data.value2);
}
php:
server.php
<?php if ($_POST["value1"] < $_POST["value2"]) {
echo $_POST["value1"]." is smaller than ".$_POST["value2"];
} else {
echo $_POST["value1"]." is bigger than ".$_POST["value2"];
}

Javascript Array not recognized within PHP - Get undefined

I am rewriting html code that is working into PHP. I am almost there but the final part is to get my tooltips working. The program lists a bunch of activities from an XML file and the schedules for these activities are also in the XML file. The tooltip uses an array to define the schedule for each activity. Putting your mouse over the activity brings up a tooltip with that activity's schedule. The tootip program was written by someone far more capable than I and was available for free and works fine in my original program. The program runs through but the tooltips are all undefined. I know my variables are working properly (though debugging) but I believe array is not as I hoped it would be. Here is a section of the code I created and I will add some of the debugging output. I suspect the array in document.write is not working as I had hoped.
My code
echo <<<EOF
<div id="table">
<table id="tbloc" border="0" width="100%">
EOF;
foreach($activities as $activity)
{
if ($cycle==1)
{
echo '<tr>';
}
$act=$activity->column;
$n = $n+1;
echo <<<EOF
<script type ="text/javascript">
var n = $n;
if (n == 1)
{
var A = new Array();
}
A[n] = "$activity->schedule";
action = "$act";
document.write('<td width="25%"><b>'+action+'</b></td>');
n=n+1;
</script>
EOF;
if ($cycle!==4)
{
$cycle=$cycle+1;
}
else
{
$cycle=1;
echo '</tr>';
}
}
?>
The debugger output form Explorer
Note: Move Mouse over desired activity to see regular scheduling for that activity
<div id="table">
<table id="tbloc" border="0" width="100%">
<tr>
<script type ="text/javascript">
var n = 1;
if (n == 1)
{
var A = new Array();
}
A[n] = "<b><u>Amateur Radio Schedule:</u></b><br />Wed 11:30am - 1:00pm<br />Wed 6:00pm - 8:30pm";
action = "Amateur Radio";
document.write('<td width="25%"><b>'+action+'</b></td>');
n=n+1;
</script>
<script type ="text/javascript">
var n = 2;
if (n == 1)
{
var A = new Array();
}
A[n] = "<b><u>Bingo Schedule:</u></b><br />Fri 12:30pm - 3:00pm";
action = "Bingo";
document.write('<td width="25%"><b>'+action+'</b></td>');
n=n+1;
</script>
<script type ="text/javascript">
var n = 3;
if (n == 1)
{
var A = new Array();
}
A[n] = "<b><u>Book Club Schedule:</u></b><br />Every 2nd Thurs 2:00pm - 3:00pm<br />Every 3rd Mon 1:00pm - 3:00pm";
action = "Book Club";
document.write('<td width="25%"><b>'+action+'</b></td>');
n=n+1;
</script>
You're putting a <script> tag inside a <tr> which shouldn't be done. The problem you're reporting is in several places where you are outputting the variable names instead of the variables.
var n = $n;
outputs as exactly that. You mean
var n = <?php echo $n; ?>
and
document.write('<td width="25%"><b>'+action+'</b></td>');
You are outputting n instead of the number it represents. This will write the variable contents instead.
document.write('<td width="25%"><b>'+action+'</b></td>');
There are many instances in your code, not just those two.
But you need to separate your JS, the smallest change to at least get it valid, though not the ideal solution, would be this:
<?php
$table=''; // this will be outputted as one string
foreach($activities as $activity){
if ($cycle==1){
$table.= '<tr>';
}
$act=$activity->column;
$n = $n+1;
?>
<script type ="text/javascript">
var n = <?php echo $n; ?>
if (n == 1){
var A = new Array();
}
A[n] = <?php echo json_encode($activity->schedule); ?>;
<?php
$table.='<td width="25%"><b>'.$act.'</b></td>';
?>
n=n+1;
</script>
<?php
} // end foreach (guessing this is where it's meant to end
?>
<div id="table">
<table id="tbloc" border="0" width="100%">
<?php echo $table; ?>
</table>
<?php
But, where does $cycle come from? There should be a </tr> somewhere...

Javascript loop create function and append value with PHP Query based id received

Below is my PHP MySQL Query and getting the last value result, I want to add 10 Javascript functions into my PHP page at end of page, however counting of variable works but I am not able to concat that value to function and other variable names.
Below is my code:
<script>
<?php
$brSql = "SELECT BRANCH_ID FROM `tb_um_client_branches` ORDER BY BRANCH_ID DESC LIMIT 1";
$brRset = mysql_query($brSql) or die('BRANCH LAST ID QUERY FAIL: '.mysql_error());
$brRID = mysql_fetch_row($brRset);
for($i = 0; $i < 10; $i++){
?>
cnter = (<?php echo $brRID[0]; ?> + <?php echo $i; ?>)
function getChecked_+cnter(){
var nodes+cnter = $('#tt_+cnter').tree('getChecked');
//var nodes = $('#tt').tree(data-options="method:'get',animate:true,checkbox:true");
var s_+cnter = '';
for(var i_+cnter=0; i_+cnter<nodes_+cnter.length; i_+cnter++){
if (s_+cnter != '') s_+cnter += ',';
s_+cnter += nodes_+cnter[i_+cnter].id + ' ' + nodes_+cnter[i_+cnter].text;
}
//$('#OLD_BRANCH_FILTERS_+cnter').value = s_+cnter;
$('#OLD_BRANCH_FILTERS_'+cnter).attr('value', s_+cnter);
//alert(s_+cnter);
}
console.log(cnter);
<?php
}
?>
</script>
Below is error, I am getting:
SyntaxError: missing ( before formal parameters
function getChecked_[cnter](){
Earliest help will be appreciated.
Thanks in advance !
This syntax
function getChecked_+cnter(){
is not valid.
You should use something of that
this["getChecked_"+cnter] = function() {
Important: there is a little difference with this declaration.

Why 'var ehy = "php echo $dunno"'?

I want to get some keyword by a textarea by using this js code. Obviously, I need PHP code too, but I have a problem with the string - var ehy = "php echo $dunno". Why this? Can anyone help me?
<?php
if (isset($_POST['line'])) {
$line = $_POST['line'];
$dunno = (explode(" ", $line));
}
?>
<script>
function countLines(){
var stringLength = document.getElementById("myText").value.length;
var count = Math.ceil( stringLength / document.getElementById("myText").cols );
// just devide the absolute string length by the amount of horizontal place and ceil it
return count;
}
function what(){
var n = countLines()
var tarea = document.getElementById('myText')
var lines = tarea.value.split("\n")
//for(var x = 0; x < lines.length; x++) {
$.ajax({
type: "POST",
url: "",
data: "line="+lines,
success: function(){
var ehy = "<?php echo $dunno; ?>"
$('#what').text(ehy)
},
});
//}
}
</script>
</head>
<body>
<h1>SearchFunction()</h1>
<textarea rows="10" cols="70" id="myText"><?php echo "what the hell?";?></textarea>
<input type="button" onclick="what()"/>
<p id="try"></p>
<p id="what"></p>
</body>
</html>
What you have there is some HTML-like page with little bits of PHP in it.
<html>
<?php echo 'hi' ?>
</html>
On your server, the php gets processed and all the tags get replaced:
<html>
hi
</html>
In your particular situation, the place where you echo $dunno is in the middle of some embedded javascript.
All of this happens on the server. The client (browser) did nothing so far.
Now that the page is ready, it gets to the browser which interprets it. The browser doesn't get the bits because they have already been interpreted. The browser simply gets a HTML with some JS:
var ehy = 5
At an even later point, when the what function is executed, it will trigger an ajax request that on success sets the text of #what to the value determined a long time ago by the PHP interpreter.
I hope that answers your question.

Categories