I am trying to create an input tag for an HtmlTemplate function for each file in a folder on my google Drive.
This input tag works, but I'm trying to use variables to set the team (BAL) and the src id:
<input type="image" class="teamLogo" onClick="getTeam('BAL');" src="https://drive.google.com/uc?id=12p5P6dmmHTX3PIq0kyUKr2qhWtSkmi3h">
This is the scriptlet in my html file:
<? var logos = getTeamLogos() ?>
<? for (i in logos) { ?>
<input type="image" class="teamLogo" onClick="getTeam('"+logos[i][0]+"');" src="https://drive.google.com/uc?id="+logos[i][1]+"">
<? } ?>
And this is the getTeamLogos function I am calling:
function getTeamLogos(){
var getLogos = DriveApp.getFolderById('redacted').getFiles();
var logos = []
while (getLogos.hasNext()) {
var logo = getLogos.next();
var teamAbbrv = logo.getName();
var logoId = logo.getId();
logos.push([teamAbbrv,logoId])
}
logos.sort()
console.log(logos)
return logos
}
Here's the console.log from the getTeamLogos function:
[ [ 'ANA', '1A8UJAYuKCter4V0gvd6nYP7z8G_QpWzK' ],
[ 'BAL', '12p5P6dmmHTX3PIq0kyUKr2qhWtSkmi3h' ],
[ 'BOS', '1AVMrn7E3fOlgFc_slCFPGQjFG2eauAKF' ],
[ 'CLE', '1yY76xP_axJfbCmEZoSx2nDlILOaoKIBg' ],
[ 'CWS', '1ZCPbHLQ_iIB8WSQ_sPYELiSw3p23uzc2' ],
[ 'DET', '1GMmqhGr1eeCfoRgNMqliHFehwTopLVQE' ],
[ 'HOU', '1iN-78qrvkT_E7K-CCUZbfdZV_o1vokPk' ],
[ 'KC', '1vd_0mby6wV9qxSA4lvzBNPFi5bLnFsf3' ],
[ 'MIN', '1HP5gArugPbXBlsCKrtYs0cPmIcff-Uf0' ],
[ 'NYY', '1VIAYsnGgIKIG9VIIkcOVib446Wh2Ue1D' ],
[ 'OAK', '1dYECC_EJwc2_e2WGJ_H5W0hvOAmv3w7V' ],
[ 'SEA', '1jRotoBam7UFoCxpOxfBncdr6-JEcsnhq' ],
[ 'TB', '10UlOIjit_K7Vmyna85aAztRuXzULnpb_' ],
[ 'TEX', '1MgZfakotrGTrOotDVCNpehAKlWo7O4wp' ],
[ 'TOR', '1RwmaPY8o5oPYs_hJCiEvvVe3NEE9Kuth' ] ]
But I keep getting a malformed HTML content error:
Exception: Malformed HTML content: <input type="image" class="teamLogo" onClick="getTeam('"+logos[i][0]+"');" src="https://drive.google.com/uc?id="+logos[i][1]+""> .
I've tried every combination of single quote, double quote, plus sign, ampersand, can't get the syntax quite right.
I thought that in your HTML, the scriptlets are required to be modified as follows.
From:
<? var logos = getTeamLogos() ?>
<? for (i in logos) { ?>
<input type="image" class="teamLogo" onClick="getTeam('"+logos[i][0]+"');" src="https://drive.google.com/uc?id="+logos[i][1]+"">
<? } ?>
To:
<? var logos = getTeamLogos() ?>
<? for (i in logos) { ?>
<input type="image" class="teamLogo" onClick="getTeam('<?= logos[i][0] ?>');" src="https://drive.google.com/uc?id=<?= logos[i][1] ?>">
<? } ?>
The scriptlets are replaced the HTML template with the values of Google Apps Script. Please be careful about this.
Note:
As additional information, in the current stage, when the loop process is used with the HTML template, the process cost will become high. Ref (Author: me) So, in your situation, I thought that the following modification might be able to be used.
HTML side
<?!= values ?>
Google Apps Script side
const html = HtmlService.createTemplateFromFile("index");
html.values = getTeamLogos().map(([a, b]) => `<input type="image" class="teamLogo" onClick="getTeam('${a}');" src="https://drive.google.com/uc?id=${b}">`).join("");
const htmlOutput = html.evaluate();
// You can use htmlOutput to Web Apps, sidebar, dialog, and so on.
Reference:
HTML Service: Templated HTML
Related
I am working on Get Instagram Stories and show them on website project. So I have done getting stories with API from facebook. I also have an javascript code to show these stories just like instagram does. But here is my question >
How can I put my php variables inside the javascript?
How javascript adds or removes stories. I mean I need some kind of "for each loop"
My php variable codes;
<?php foreach ( $stories as $story ) : // loop over each story element ?>
<?php if ( 'VIDEO' == $story['media_info']['media_type'] ) : // story media is a video ?>
<div>
<video controls poster="<?php echo $story['media_info']['thumbnail_url']; ?>" style="max-width:300px">
<source src="<?php echo $story['media_info']['media_url']; ?>" />
</video>
</div>
<?php elseif ( 'IMAGE' == $story['media_info']['media_type'] ) : // story media is an image ?>
<div>
<img src="<?php echo $story['media_info']['media_url']; ?>" style="max-width:300px" />
</div>
<?php endif; ?>
<div>
<b>
<?php echo $story['media_info']['username']; ?>
</b>
</div>
<a href="<?php echo $story['media_info']['permalink']; ?>" target="_blank">
View on Instagram
</a>
<?php endforeach; ?>
My javascript code;
stories: [
Zuck.buildTimelineItem(
"ramon",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/users/1.jpg",
"Ramon",
"https://ramon.codes",
timestamp(),
[
[
"ramon-1",
"photo",
3,
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/1.jpg",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/1.jpg",
"",
false,
false,
timestamp()
],
[
"ramon-2",
"video",
0,
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/2.mp4",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/2.jpg",
"",
false,
false,
timestamp()
],
[
"ramon-3",
"photo",
3,
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/3.png",
"https://raw.githubusercontent.com/ramon82/assets/master/zuck.js/stories/3.png",
"https://ramon.codes",
"Visit my Portfolio",
false,
timestamp()
]
]
)
]
Just use PHP as a proxy and pass the JSON to the JS
Otherwise you have to do something like this
{
id: "storyid", // story id
photo: "..", // story photo (or user photo)
link: "", // story link (useless on story generated by script)
lastUpdated: "", // last updated date in unix time format
seen: false, // set true if user has opened
items: [ // array of items
// story item example
<?php
$cnt = 0;
foreach ( $stories as $story ) : // loop over each story element
?> {
id: "item<$cnt++ ?>", // item id
type: "<?= $story['media_info']['media_type'] ?>", // photo or video
length: 10, // photo timeout or video length in seconds - uses 3 seconds timeout for images if not set
src: "<?= $story['media_info']['media_url']; ?>", // photo or video src
preview: "", // optional - item thumbnail to show in the story carousel instead of the story defined image
link: "<?= $story['media_info']['permalink'];?>", // a link to click on story
linkText: "", // link text
time: "", // optional a date to display with the story item. unix timestamp are converted to "time ago" format
seen: false // set true if current user was read,
[customKey]: "", // custom-value
[anotherCustomKey]: "" // another-custom-value
}
<?php endforeach; ?>
]
}
How do i show multiple database entries in loop ? So that it looks like this:
But with multiple markers.
I'm not able to loop javascript in php to show multiple markers. Is it possible to do so?
dataProvider: {
map: "worldLow",
images: [
<?php include ('query.php');
while($row= mysql_fetch_array($fetch)){
$cty = $row['city'];
$lat = $row['lati'];
$lon = $row['longi'];
}?>
{
zoomLevel: 5,
scale: 0.5,
title: "<?php echo $cty;?>",
latitude: <?php echo $lon;?>,
longitude: <?php echo $lat;?>
}]
}
I advise you to use json_encode function so as to avoid problems with extra quotes and other symbols:
dataProvider: {
map: "worldLow",
<?php include ('query.php');
// store all markers here
$markers = array();
while ($row= mysql_fetch_array($fetch)) {
// add new marker data
$markers[] = array(
'zoomLevel' => 5,
'scale' => 0.5,
'title' => $row['city'],
'latitude' => $row['lati'],
'longitude' => $row['longi'],
);
}?>
images: <?=json_encode($markers)?>
}
For further debugging - use developers console and/or see rendered javascript.
I need Multiple CKEditor in IFRAME Yii.
I have followed the
link
its works for Without IFRAME but I have a popup dialog with an IFrame
Iframe works with Single instance editor but i need it mulipte
Code for Single Instance :
<?php echo $form->textArea($model, 'message', array('id'=>'question_editor','maxlength'=>508)); ?>
<script src="<?php echo Yii::app()->baseUrl.'/assets/ckeditor/ckeditor.js'; ?>"></script>
<script type="text/javascript">
CKEDITOR.config.toolbar_MA=[ ['Format','Bold','Italic','Underline','-','Superscript','-','JustifyLeft','JustifyCenter','JustifyRight','JustifyBlock','-','NumberedList','BulletedList','-','Outdent','Indent'] ,{ name: 'links', items: [ 'Link', 'Unlink', 'Anchor' ] },{ name: 'colors', items: [ 'TextColor', 'BGColor' ] },{name: 'insert',items:['Table','Image']},['Templates']];
CKEDITOR.replace( 'question_editor', { toolbar:'MA', height:'140px',width: '95%' } );
</script>
Please anyone help me to proceed for Multiple CKEditor instance in IFRAME
Create another text area using Yii code or HTML, change the name and id per your naming convention
<textarea name="question_editor2" id="question_editor2" rows="10" cols="80">
This is second editor.
</textarea>
Replace the textarea with CKEDITOR
<script>
CKEDITOR.replace( 'question_editor2' );
</script>
I'm trying to call a list of my Wordpress posts and save them to a Javascript array of objects (JSON, really). I want something like:
var articles = [
{
title: 'Title 1',
author: 'Author 1',
byline: 'Byline 1'
},{
title: 'Title 2',
author: 'Author 2',
byline: 'Byline 2'
}
]
I'm new to PHP so don't quite understand how looping in and out of the <?php ?> tags works, nor how variables and functions work in this sense. I'm trying the following:
<script>
var articles = [];
<?php
$args = array( 'numberposts' => -1);
$posts= get_posts( $args );
if ($posts) {
foreach ( $posts as $post ) { ?> // exit PHP
var obj = {}; // Create a JS object
obj.title = <?php the_title(); ?>; // Append the title to the object
obj.byline = <?php the_excerpt(); ?>; // Append the byline
articles.push(obj); // Push object into the array
<?php }
}
?>
</script>
I have the following code to pass a Javascript array to PHP using ajax :
in HTML :
echo "<input type=\"hidden\" id= \"que_id\" name= \"que_id[]\" value=".$questions['que_id'].">";
This is inside a loop.
in Javascript :
var que_id_array = new Array();
$('input[name="que_id[]"]').each(function(){
que_id_array.push($(this).val());
});
AJAX Call :
$.ajax({
type:"POST",
url: 'questionmastermodify.php',
data: { que_id:que_id_array},
success: function(data) {
$('.my_update_panel').html(data);
$('#overlay').fadeOut();
}
});
in PHP :
$que_id = $_REQUEST['que_id'];
echo count($que_id);
The count displays 1 and not the size of the array, whereas in Javascript the console shows :
console.log(que_id_array);
output :
["151", "152", "153", "154", "155", "156", "157", "158", "159", "160", "161", "162", "163", "164", "165", "166", "167", "168", "169", "170", "171", "172", "173", "174", "175", "176", "177", "178", "179", "180", "181", "182", "183", "184", "185", "186", "187", "188", "189", "190", "191", "192", "193", "194", "195", "196", "197", "198", "199", "200"]
I am stuck as i need this array in PHP but unable to pass this array from JS to PHP.
Thanks in advance....
Sandy505
I made a quick test with your code... and with a few changes, It work's for me.
Take a look at your code, specially the loop when you create the <input> fields...
And also.. in the loop you have an ID in the <input>... that's not good at all!.. change it for class for example...
As an example, this is what I tried:
Main PHP
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<script src="http://code.jquery.com/jquery-1.9.0.min.js"></script>
<script type="text/javascript">
jQuery(document).ready(function() {
$('#theForm').submit(function(event) {
event.preventDefault();
createTheArray();
});
});
function createTheArray(){
// Create the Array
var que_id_array = new Array();
$('input[name="que_id[]"]').each(function(){
que_id_array.push($(this).val());
});
console.log(que_id_array); // output ["151", "152", "153"]
sendTheForm(que_id_array); // do the ajax call
}
function sendTheForm(que_id_array){
// AJAX Call
$.ajax({
type:"POST",
url: 'questionmastermodify.php',
data: { que_id:que_id_array},
success: function(data) {
$('.my_update_panel').html(data);
}
});
}
</script>
</head>
<body>
<form id="theForm">
<?php
// your original Array
$arrayName = array(
array('que_id' => '151'),
array('que_id' => '152'),
array('que_id' => '153')
);
foreach ($arrayName as $key => $questions) {
echo "<input type='text' class='que_id' name='que_id[]' value='{$questions['que_id']}'>";
}
?>
<input type="submit" value="send" />
</form>
<div class="my_update_panel">result will be loaded here...</div>
</body>
</html>
And your questionmastermodify.php PHP file
<?PHP
$que_id = $_REQUEST['que_id'];
echo '<pre>';
print_r($que_id);
echo '</pre>';
?>
Result
After form submit.. the HTML will print out:
<pre>Array
(
[0] => 151
[1] => 152
[2] => 153
)
</pre>
And in the console.log();
["151", "152", "153"]
Give a try and good luck!
You could encode the array into JSON:
data: { que_id: JSON.stringify(que_id_array)},
In the PHP, decode it:
$que_id = json_decode($_REQUEST['que_id']);
echo count($que_id);
The problem has been sorted out :
The culprit was the version of the jquery i was using. I was using jQuery JavaScript Library v1.3.2 - which caused this problem.
Using the latest : jquery-1.9.0.min.js solve the problem.
I am accepting the answer provided by #gmo as it brought me near to the problem solving and also about that helpful tip about not using id attribute in the Loop...
Thanks all...