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...
Related
I don't have a lot of experience with Javascript and Ajax or JSON for that matter but I'm currently building an HTML lookup tool for a simple PostgreSQL database and I'm a little stuck here.
I want to fill the selectbox on the right with corresponding form names from our database whenever the user selects the study in the left selectbox
However, I have problems to process the array that I get back from the PHP script.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery/3.2.1.min.js"</script>
<script>
function getselect(value) {
$.ajax(
{
type: "GET",
url: 'getforms.php',
data: {value: value},
dataType: "json",
success: fillbox
});
}
function fillbox(data) {
var forms = $('#forms');
var arr = $.parseJSON(data);
for (var x = 0; x < arr.length; x++) {
forms.append(new Option(arr[x]));
}
}
</script>
</head>
<body>
[...]
<?php
$snames = $conn->prepare("SELECT DISTINCT studienname FROM public.fulldict");
$snames->execute();
$a=$snames->fetchAll(PDO::FETCH_COLUMN, 0);
?>
<table border="0">
<tr>
<th>Studien:</th>
<th>Formulare:</th>
</tr>
<tr>
<td>
<select id="study" name="Studien" size="12" onchange="getselect(this.value);">
<?php foreach($a as $option) { ?>
<option value="<?php echo $option ?>"> <?php echo $option ?> </option>
<?php }?>
</select>
</td>
<td>
<select id="forms"></select>
</td>
</tr>
</table>
?>
</body>
</html>
The getforms.php is intended to handle the SQL-query and send an array of values from the database back to Javascript, where the 'fillbox' function is supposed to fill the select box with the values from the array.
<?php
$f = $_GET['value'];
// Connect to Database
require_once 'dbconfig.php';
$dsn = "pgsql:host=$host;port=5432;dbname=$db;user=$username;password=$password";
$conn = new PDO($dsn);
// Get array with form names
$form_arr=array();
$fnames = $conn->prepare("SELECT DISTINCT formular FROM public.fulldict WHERE studienname = '$f'");
$fnames->execute();
$form_arr=$fnames->fetchAll(PDO::FETCH_COLUMN, 0);
echo json_encode($form_arr);
?>
When I run the code and select anything from the first selectbox nothing happens. Am I doing something wrong accessing the second selectbox?
Any help is appreciated.
Thanks guys, I got it to work. After addiing the JSON header in the PHP file. I had to change the fillbox function to
function fillbox(data) {
var options = '';
for (var x = 0; x < data.length; x++) {
options += '<option value="' + data[x] + '">' + data[x] + '</option>';
}
$('#forms').html(options);}
Still don't quite understand why the '.append(new Option())' stuff didn't work though?
I have a code that looks like this.
<script>
function loadmainTBL(){
<? var data = SpreadsheetApp
.getActiveSpreadsheet().getSheetByName("Customer Logs Information Database")
.getDataRange()
.getValues(); ?>
var number = 6
<?for (var i = 12; i < data.length; i++) { ?>
<? if (data[i][0] == "I want to put it here") { ?>
var tableHeaderRowCount = 1;
var table = document.getElementById('TableContainer');
var rowCount = table.rows.length;
for (var i = tableHeaderRowCount; i < rowCount; i++) {
table.deleteRow(tableHeaderRowCount);
}
<?}?>
<?}?>
}
</script>
as you can see this code is inside html file and it is compose of javascript and google scriptlet my question is this. how can I pass this?
var number = 6
in this one?
<? if (data[i][0] == "I want to put it here") { ?>
Here is the html code.
<? var data = SpreadsheetApp
.getActiveSpreadsheet().getSheetByName("Customer Logs Information Database")
.getDataRange()
.getValues(); ?>
<table id = "TableContainer" cellspacing="2" cellpadding="3" width ="100%" align = "center" class="hoverTable">
<th bgcolor = "darkgreen"><font color="white">#</font></th>
<th bgcolor = "darkgreen"><font color="white">Area</font></th>
<th bgcolor = "darkgreen"><font color="white">Customer Name</font></th>
<th bgcolor = "darkgreen"><font color="white">Person In Charge</font></th>
<th bgcolor = "darkgreen"><font color="white">Remarks</font></th>
<th bgcolor = "darkgreen"><font color="white">Status</font></th>
<th bgcolor = "darkgreen"><font color="white">Doc. Date</font></th>
<th bgcolor = "darkgreen"></th>
<? for (var i = 12; i < data.length; i++) { ?>
<tr>
<td class="dataid"><?= data[i][0] ?></td>
<td class="area"><?= data[i][1] ?></td>
<td class="cusname"><?= data[i][2] ?></td>
<td class="cic" width = "200px"><?= data[i][3] ?></td>
<td class="remarks" ><?= data[i][4] ?></td>
<td class="status" width = "70px"><?= data[i][5] ?></td>
<td class="docdate"><?= data[i][6] ?></td>
<td ><img class="click-to-select" src="https://docs.google.com/uc?id=0By6kUPbaVMWCbUI0LTJTR2g2N3M" alt="Submit" width="13px" height="13px" title = "Edit Selected Data" data-toggle="modal" data-target="#myModal"/>
</td>
<? } ?>
</tr>
</table>
tysm for future help.
In code.gs before anything else, place the following:
//Define this here globally so it is accessed in the HTML Template
var passedParameter= ' ';
You can define this to equal 6, or inside a function define it based on some code prior to creating the page. In my case, I am deploying this as a web app and passing two variables via the URL, which I then merge and save so my client side has access:
/**-----------------------------------------------------------------------------------
|
| Begin section for app interface
|
------------------------------------------------------------------------------------*/
// Script-as-app template.
function doGet(passed) {
if(passed.parameter.festival && passed.parameter.year){
Logger.log(passed.parameter);
passedParameter = passed.parameter.festival + ' ' + passed.parameter.year;
}
var result=HtmlService.createTemplateFromFile('GridView').evaluate()
.setTitle('Boxwood Registrations')
.setWidth(1285)
.setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
return result;
}
The above 2 sections of code are my entire code.gs file. When I run the web app in my browser I add this to the end of web app's url:
?festival=myfestival&year=2017
My HTML files now have access to a variable called passedParameter which is equal to "myfestival 2017" which I access in a function in my HTML with:
<script>
function showMenuYear(menuItems) {
var list = $('#optionListYear');
var desiredValue = '<?!= passedParameter ?>';
//More code here to use the variable desiredValue
}
</script>
If I need to retrieve more information from the server side after user input, such as read a spreadsheet for a value, I use this in a function in the html file:
<script>
function setFormList() {
var replacement = document.getElementById("OverallGrid");
replacement.innerHTML = "Retrieving Data...";
if ($('#optionListYear').val() === "-1") {
replacement.innerHTML = "Select a Festival/Year above.";
return;
}
//Run the function getValidRegistrations() which is in a .gs file (server side), passing the value of the element optionListYear.
google.script.run.withSuccessHandler(showRegistrationsTable).withFailureHandler(loadFailed).getValidRegistrations($('#optionListYear').val());
}
//If the server side ran succesfully, this is run
function showRegistrationsTable(returnedItem){
//My code to work with the returned item goes here
}
//If the server side failed for some reason an error will be returned
function loadFailed(returnedError){
//My code to display a error message with the returned item goes here
}
</script>
So I am trying to make a simple academic system.
I made dynamic boxes which show course information.
Core code looks like this
function addcourses(){ //(numcourses)
var num_courses= <?php echo $_GET['num']?>; //=numcourses
var newdiv;
var divIdName;
var i=0;
for(i=1;i<=num_courses;i++){
var divtoadd = document.getElementById('courselist');
newarticle = document.createElement('article');
divIdName = 'course'+i;
newarticle.setAttribute('id',divIdName);
newarticle.innerHTML ='<div class="box"><h2><?php echo $course_num_arr[i]?></h2><div class="content"><p>Credit Hours: <?php echo $credit_arr[0]?> </p><p>Professor: <?php echo $prof_arr[0]?></p><p>Average GPA: <?php echo $avg_arr[0]?></p><p>GPA: <?php echo $gpa_arr[0]?></p></div></div>';
call_course();
divtoadd.appendChild(newarticle);
}
}
The problem is with <?php echo $course_num_arr[i]?> since i is the variable from javascript, I don't know how to deal with this.
I want to echo $course_num_arr[1] when i = 1 and $course_num_arr[2] when i = 2 and so on.
If you don't want to use ajax call and wants to place the code in the PHP file, your can use json_encode() function. Please refer below code.
<?php
$cources = array( "0" => array ("name" => "maths","credits" => 30),"1"
=> array ("name" => "physics","credits" => 30));
?>
<script>
data=<?php echo json_encode($cources); ?>;
for(i=0;i<data.length;i++){
alert(data[i].name)
var h = document.createElement("H1");
var t = document.createTextNode(data[i].name);
h.appendChild(t);
document.body.appendChild(h);
}
</script>
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)+"%":"";
}
}
I am trying to pre-load onClick images, and the script works except in Google Chrome (and I imagine Safari)... not sure what is going on. Anyone have any ideas?
<div style="display:hidden">
<script type="text/javascript">
<!--//--><![CDATA[//><!--
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
<?php
for ($i = 0; $i < 6; $i++) {
if (!empty($imgs[$i])) {
$comma = $i == 0? '' : ',';
echo $comma."'http://www.htpcusa.com/drcom/ebay/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=500'";
}
}
?>
)
//--><!]]>
</script>
</div>
Images are being called later to via this code.
<?php
for ($i = 0; $i < 6; $i++) {
if (!empty($imgs[$i])) {
echo "<div class=\"htpc_picturebox\">";
echo "<img id=\"imgs$i\" src=\"http://www.htpcusa.com/drcom/ebay/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=157\" alt=\"\"";
echo " onClick=\"javascript:document.getElementById('detailed_image').src='http://www.htpcusa.com/drcom/ebay/image.php?img_source_url=" . $imgs[$i] . "&img_resize_to=500';\" />";
echo "</div>";
}
}
?>
So what is Chrome not doing, that IE and FF recognize!?
its arguments.length and not functionname.arguments.length
and array syntax is var images = [] but besides that it looks like its working jsfiddle
preload function doesn't take any argument in definition but you're trying to send parameters. Instead of sending parameters to preload function through php output, you may initialize images array through php output. eg;
<?
$i=0;
while (something) {
echo "images[{$i}] = {$img}";
$i++;
?>