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
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>
when i try dd($conv) the data are there, but I still can't display them inside the script.
Anyone know whats the problem, I have tried many ways but they doesn't seem to work.
<h4>{{$row->transcript_text}}</h4>
<?php $conv = json_encode($row->transcript_text); ?>
<script type="text/javascript">
function splitArray() {
var myStr = <?php echo $conv; ?>;
var strArray = myStr.split(/(?= \| \d)/);
// Display array values on page
for (var i = 0; i < strArray.length; i++) {
$("body").addClass('col-lg-offset-1').append("<h4>" + strArray[i] + "</h4>");
})
}
splitArray();
</script>
I don't know which version of Laravel you're using but the recommended way to embed plain PHP in your HTML templates is with the #php notation (cf doc).
Anyway, that's something I'd try to avoid. Instead, Laravel blade has native ways of doing what you're trying to do.
#if(! empty($history))
#foreach($history as $row)
<script type="text/javascript">
function splitArray() {
var myStr = JSON.parse("{{json_encode($row->transcript_text) }}");
var strArray = myStr.split(" | 0");
// Display array values on page
for (var i = 0; i < strArray.length; i++) {
$("body").addClass('col-lg-offset-1').append("<h4>" + strArray[i] + "</h4>");
}
}
</script>
<body onload="splitArray()" style="color: lime">
</body>
#endforeach
I have to create a dropdown list and a button that will add another dropdownlist once click. i used this javascript code:
var array = ["Volvo","Saab","Mercades","Audi"];
var cell2 = row.insertCell(1);
var element2 = document.createElement("select");
element2.name="activity_dropdown"
element2.id="activity_dropdown"
cell2.appendChild(element2);
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.setAttribute("value", array[i]);
option.text = array[i];
element2.appendChild(option);
}
but i want that my var array will come from the database result query. what can i do to pass php array to javascript array?
by the way.. i have tried to used json_encode but it seems not working.. here is the my code:
for data.php
<?php
include('connection/dbConn.php');
// get data and store in a json array
$activity=$conn->query("SELECT activity_name FROM rehab_activities");
while ($row =mysqli_fetch_array($activity)) {
$activities[] = array(
'actvityName' => $row['activity_name']
);
}
echo json_encode($activities);
?>
and try it here, but nothing comes out:
<script>
jQuery(document).ready(function(){
jQuery("#add").click(function(){
var res = new Array();
jQuery.getJSON("data.php", function(data) {
var i= 0;
while(i<data.myarray.length){
res[i]=data.myarray[i];
i++;
}
jQuery("#result").html(res[0]);
});
});
});
</script>
<body>
<input type="button" id="add">
<div id="result"></div>
</body>
</html>
Make php write that part of your script while it loops through your query. Like so:
var array = [
<?php
$query = mysql_query("SELECT * FROM cars");
while ($car = mysql_fetch_assoc($query)) {
$car_name = $car["name"];
echo "'$car_name',";
}
?>
];
For this to work, your file must be a php file and not a javascript file, since inside a php file you can also write html and therefore, javascript.
I personally solve this by making a file called db-to-js.php that only contains javascript arrays created by php. Whenever the database is modified, one or more of these javascript arrays are also modified since they are created every time this file is executed.
Lastly, you have to include the file where you need it as a script:
<script type="text/javascript" src="db-to-js.php"></script>
I hope this helps.
I had a similar problem in vue js, renamed my 'app.js' file to 'app.php', where i added all my php functions and changed the reference script tag to
<script> type='text/javascript' src='app.php' </script>
Worked For me!
In general: What I want is to have PHP output an unordered list with books. When the user clicks on one of the titles, the details will be pulled from the DB and inserted into the page using AJAX.
I can't seem to figure out how to pull the title value from the < li > using javascript, so I can pass that to AJAX.
(To simplify the example code, I left out the AJAX part and am using an alert instead.)
<html>
<head>
<script type="text/javascript">
window.onload = function()
{
var shelve = document.getElementById( 'books' );
var books = shelve.getElementsByTagName( 'li' );
for( var i=0; i < books.length; i++ ){
books[i].onclick = function(){
alert(books[i].title); //I know this doesn't work
};
}
}
</script>
</head>
<body>
<div id="txtHint"><b>Book info will be listed here using AJAX.</b></div>
<?php show_allBooks(); ?>
</body>
</html>
<?php
function show_allBooks(){
db_connect();
$query = "Select * from tblBooks order by title";
$result = mysql_query($query);
echo "<ul id='books'>";
while ($row = mysql_fetch_array($result))
{
echo "<li title='" . $row['id'] . "'>" . $row['title'] . "</li>";
}
echo "</ul>";
db_close();
}
?>
I tried fooling around with variations of the following code, but this did not seem to work either.
books[i].getAttribute("title")
Can anyone point me in the right direction? Any help would be greatly appreciated.
By the time your onclick handler gets called, i has been incremented to books.length. Instead, you can reference this to get the element.
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = function () {
alert(this.title);
};
}
http://jsfiddle.net/gilly3/cPMAU/
However, if you do need to know the value of i in the click handler, you can do it by creating your handler in a factory, that is a function that returns a function:
function createBookHandler(books, i) {
return function() {
alert(books[i].title);
};
}
var shelve = document.getElementById('books');
var books = shelve.getElementsByTagName('li');
for(var i = 0; i < books.length; i++) {
books[i].onclick = createBookHandler(books, i);
}
http://jsfiddle.net/gilly3/cPMAU/1/
Start with
books.item(i)
Then it depends how title is stored in the list. If its
<li title="">
then
books.item(i).getAttribute("title")
But the closure related answer is probably more important.