How to pass javascript variable in google scriptlet? - javascript

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>

Related

How to delete row in html based on cell value

I am trying to delete a row based on a table's cell value.
In my HTML page I have a simple search function. It would send the values in the text box to the database through ajax then PHP and then PHP would create a table dynamically based on what is in the database.
I have tried to check a the cell in the table for a specific value so that if it is true then the current row would be removed, the function name is checkMatch(). However it doesn't work.
This is the button in the HTML, the rest of the HTML is just a text box and drop down box:
<input type="button" id="device_search" value="Search" onclick="searchDevice(); checkMatch();"></input>
This is the function in the external JavaScript file:
function checkMatch()
{
var row = document.getElementById("thisRow");
var cell = Row.getElementById("match");
if(cell[0].innerText = "0%")
{
row.deleteRow(this);
}
}
And here's the creating of table in the PHP:
if($num_row)
{
echo "<table id=\"myTable\" border=\"1\">";
echo "<tr>
<th>Board ID</th>
<th>Tester Name</th>
<th>Board Name</th>
<th>Current Slot</th>
<th>Log Created</th>
<th>Required Slot</th>
<th>Match</th>
</tr>";
while($row = mysql_fetch_assoc($result))
{
$board_id = $row['board_id'];
$tester_name = $row['tester_name'];
$board_name = $row['board_name'];
$config = $row['config'];
$log_created = $row['log_created'];
$req_config = $row['configuration'];
$exploded = explode(",", $req_config);
$count = count($exploded);
$j = 0;
foreach($exploded as $value)
{
$number = strlen($value);
$arr = str_split($value, $number);
if(in_array($config, $arr))
{
$j += 1;
$j /= ($count / 100);
echo $j;
}
else
{
}
}
echo "<tr id = \"thisRow\">
<td>$board_id</td>
<td>$tester_name</td>
<td>$board_name</td>
<td>$config</td>
<td>$log_created</td>
<td>$req_config</td>
<td id = \"match\">$j%</td>
</tr>";
}
echo "</table>";
}
The column that I'm checking on is the last column which is the Match column. My idea is to remove that current row whenever the cell value of Match is 0%. I can't seem to find what's wrong with my codes, I'm not really good at manipulating DOM elements either so there must be some mistake. Any help on this? Or are there others ways, through PHP etc?
Note: I am not trying to delete the row from database. I just want to remove the row whenever Match is 0%.
EDIT, codes for searchDevice() in external js file:
function searchDevice()
{
var device_name = $("#device_name").val();
var tester_type = $("#tester_type").val();
var page = "database.php";
if(device_name==""||tester_type=="")
{
alert("Please do not leave any blanks.");
}
else
{
$.post(page, {
device_name : device_name,
tester_type : tester_type,
action : "search"
}, function(data) {
$("div#display_board").html(data);
checkMatch();
});
}
}
Currently my table does display with all the right values, but it doesn't remove the rows with 0%.
checkMatch() should be called at ajax success callback
id should be unique with in HTML document
PHP
// use `class` instead of `id`
echo "<tr class=\"thisRow\">
<td>$board_id</td>
<td>$tester_name</td>
<td>$board_name</td>
<td>$config</td>
<td>$log_created</td>
<td>$req_config</td>
<td class=\"match\">$j%</td>
</tr>";
Javascript
function checkMatch()
{
$("#myTable tr.thisRow").each(function() {
var thisRow = $(this);
var match = thisRow.find(".match");
// note the `==` operator
if(match.text() == "0%") {
thisRow.hide();
// OR thisRow.remove();
}
});
}

Passing values of array into HTML text box

Let say I have a function that populates an array
function 1(){
var array = []
//do things
//array.push("stuffs")
How can I pass or iterate through this array into an HTML text box?
Edit for clarity
I am working with google apps script.
I have a .gs file which runs server side.
I have an .html file which populates my UI.
In the .gs file I am populating an array based on information from a google sheet.
once I have this array I want to populate a text box in the .html file.
I am about 12 hours into html so I may not even understand this enough to articulate my questions correctly.
var html = '';
var array=['apple', 'peach','pear'];
$.each(array, function(index, item){
html+='<input type="text" value="' + item + '"/>';
});
$('body').append(html);
FIDDLE
Code.gs:
function doGet() {
var t = HtmlService.createTemplateFromFile('index');
t.data = SpreadsheetApp
.openById('1234567890abcdefghijklmnopqrstuvwxyz')
.getActiveSheet()
.getDataRange()
.getValues();
return t.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME);
}
index.html:
<table>
<? for (var i = 0; i < data.length; i++) { ?>
<tr>
<? for (var j = 0; j < data[i].length; j++) { ?>
<td><?= data[i][j] ?></td>
<? } ?>
</tr>
<? } ?>
</table>
You can use same for input i guess.
Reference

Best way to fetch a PHP array and output the result with jQuery?

I am trying to grab some text from a MyBB forum's exported messages. The file is a CSV file.
if (($handle = fopen("test.csv", "r")) === FALSE) {
exit("Couldn't load CSV");
}
fgetcsv($handle);
$messages = array();
$i = 0;
while($data = fgetcsv($handle)){
if(count($data) == 7){
$messages[$i]['date'] = $data[0] + "," + $data[1];
$messages[$i]['folder'] = $data[2];
$messages[$i]['subject'] = $data[3];
$messages[$i]['receiver'] = $data[4];
$messages[$i]['sender'] = $data[5];
$messages[$i]['message'] = str_replace("\'", "'", $data[6]);
}else{
$messages[$i]['date'] = $data[0];
$messages[$i]['folder'] = $data[1];
$messages[$i]['subject'] = $data[2];
$messages[$i]['receiver'] = $data[3];
$messages[$i]['sender'] = $data[4];
$messages[$i]['message'] = str_replace("\'", "'", $data[5]);
}
$i++;
}
I gave each tr and th tag (th includes the name of the sender and tr includes the message) a class with a number. First message is 0, second is 1, third is 2 and so on. I load the message in PHP like this:
$messages[0]['message'])
Where 0 is the first message. I want it to be like when I click on first message, it loads the first. When I click the second, it loads the second message. You get the idea.
My jQuery is as following:
$("td, th").on("click", function() {
var message = $(this).attr("class");
$("#message").text("<?= preg_replace("/\r|\n/", "", $messages[0]['message']) ?>");
});
I use preg_replace to get it all into one line.
Foreach loop
<table>
foreach($messages as $i => $message) {
echo <<<EOL
<tr>
<th class="$i"> {$message['sender']} </th>
</tr>
<tr>
<td class="$i"> {$message['message']} </td>
</tr>
EOL;
}
</table>
So to sum up: I want to display the message when I click the message in the table, but I am not sure what would be the best approach to do that.
$("td, th").on("click", function() {
var messageId = $(this).attr("class");
$.ajax({
url: "test.php",
type: "post",
data: messageId,
success: function(returnedVal){
$("#result").html(returnedVal);
},
error:function(){
$("#result").html('There is an error');
}
});
});
returnedVal is the value returned by your test.php.
For example, you can return your message.
Then you display it in $("#result") or wherever you want :)

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...

Pass the td value to php page using Javascript

I have a HTML table the displays record from database.
Below is a screenshot of my table
There is a button in a TD (i.e column 5,7,9), when I click the button I want to perform function to display a popup box with html table.
Before that I want to pass the value of mcc and mnc and also want to pass the column name (i.e if i clicked the button near 5xx i want pass 5xx if 6xx I want to pass 6xx) to the page where there is a query to display the table. And have separate php code to retrieve th and td from database.
I tried but I don't know how to pass this value to javascript then to php page that contains query to display the table. Thanks
This is my HTML markup:
<table>
<th style="text-align:center;width:92px">MCC</th>
<th style="text-align:center;width:92px">MNC</th>
<th style="text-align:center;width:92px">MNP</th>
<?
$ColumnNames = mysql_query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = 'supplierprice' AND column_name NOT
IN ('supp_price_id','region', 'country', 'networkname', 'mcc', 'mnc', 'mnp'
)") or die("mysql error");
$columnArray=array();
$i = 0;
while($rows = mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows[0];
echo "<th>" . $columnArray[$i] . " <span> <img id='logo' src='/image/Picture2.png' style='margin:-62px -21px -9px 32px'></span></th>";
echo "<th style= 'width:20px;'></th>";
$i++;
}
?>
<?php
$sql = mysql_query("SELECT * FROM supplierprice ");
while($rows=mysql_fetch_array($sql))
{
if($alt == 1)
{
echo '<tr class="alt">';
$alt = 0;
}
else
{
echo '<tr>';
$alt = 1;
}
echo ' <td class="edit region '.$rows["supp_price_id"].'">'.$rows["region"].'</td>
<td class="edit country '.$rows["supp_price_id"].'">'.$rows["country"].'</td>
<td class="edit networkname '.$rows["supp_price_id"].'">'.$rows["networkname"].'</td>
<td id="mcc" class="edit mcc '.$rows["supp_price_id"].'">'.$rows["mcc"].'</td>
<td id="mnc" class="edit mnc '.$rows["supp_price_id"].'">'.$rows["mnc"].'</td>
<td class="edit mnp '.$rows["supp_price_id"].'">'.$rows["mnp"].'</td>';
$ColumnNames = mysql_query("SELECT column_name FROM information_schema.COLUMNS WHERE table_name = 'supplierprice' AND column_name NOT
IN ('supp_price_id','region', 'country', 'networkname', 'mcc', 'mnc', 'mnp'
)") or die("mysql error");
$columnArray=array();
$i=0;
while($rows1=mysql_fetch_array($ColumnNames))
{
$columnArray[]=$rows1[0];
echo '<td width="0px;" class="edit '.$columnArray[$i].' '.$rows["supp_price_id"].'">'.$rows[$columnArray[$i]].'</td>';
echo '<td><input type="button" onclick="myFunction()" value="" /></td>';
$i++;
}
echo '</tr>';
} ?>
</table>
Javascript
<script>
function myFunction() {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "testpage2/config.php";
var mcc = document.getElementById("mcc").value;
var mnc = document.getElementById("mnc").value;
var vars = "mcc="+mcc+"&mnc="+mnc;
hr.open("POST", url, true);
hr.send(vars);
}
</script>
but it not passing the value of mcc and mnc also the column
First of all assign Id to table:
<table>
like:
<table id="contentTable">
Now use below code of jQuery:
$(document).ready(function ()
{
$('#tableId').find('th').each(function ()
{
$(this).click(function ()
{
var thValue = $(this).html();
alert(thValue) // here is value of th on you have click
});
});
});
Cheers!!!
You could try to use something like "generic javascript":
<?php //some stuff
$mcc = "some value";
?>
<script type="text/javascript">
var myVariable = <?php echo $mss; ?>
</script>

Categories