Calling javascript variables from a separate HTML/php file - javascript

I have a separate javascript file(buy.js) from my html file(pay.php) that the html file posts to once a form is submitted. However, there are some javascript variables in pay.php that are outside the scope of the form that I need to call in the separate javascript file (buy.js). Is this possible to do?
This is the snippet of javascript that I need to access in my html file (buy.js):
var planTerm = term;
This is the javascript in the html that I need the separate javascript file to access (pay.php):
var term = 0;
var price = 0;
function updatePrice(e) {
price = parseFloat(select.value);
if (price == select.options[1].value){
term = 12;
} else if (price == select.options[2].value) {
term = 1;
}
}
Here is a Pastie of all the code.

Using PHP you can simply do (using the include() function):
include("File.php");
So, as my example goes,
The JS_INCLUDE.php File:
<html>
<body>
<script>
var JSvar = "This is a external JS var.";
</script>
</body>
</html>
The index.php
<html>
<body>
<?php
include("JS_INCLUDE.php");
?>
<script>
document.write(JSvar);
</script>
</body>
</html>
But of course if the .php file is remote from the directory, you cannot.
Sources:
Include() function: http://www.php.net/manual/en/function.include.php

Related

Modify script to get sheet folder ID

I would like some help to modify this script here: Upload multiple large files to Google Drive using Google Apps Script
The question is the following: this script uploads to a folder within the folder defined in const uploadParentFolderId = "1cOe4ZXjBUZHgPwADg1QRpUzcQqGxON_4"; which is in the forms.html file, the problem is that I intend to call this script within a spreadsheet through an html alert and I would like that the file was uploaded inside a folder of the spreadsheet folder, that is, the script would need to get the ID of the spreadsheet folder.
Javascript is a language that is a little out of my daily life, but I'm trying to learn it on my own...
If anyone can give me a light on this, it will be of great help!
EDIT:
I tried this:
var ssid = SpreadsheetApp.getActiveSpreadsheet().getId();
var AllFolders = DriveApp.getFileById(ssid).getParents();
var ChildFolderTest;
if (AllFolders.hasNext()) {
ChildFolderTest = AllFolders.next();
var FinalFolderID = ChildFolderTest.getId();
}
const chunkSize = 5242880;
const uploadParentFolderId = FinalFolderID; // creates a folder inside of this folder
But for some reason it doesn't work, the upload doesn't start.
Any idea how to resolve?
Here is an example of how to get the spreadsheet folder id.
form.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input id="uploadParentFolderId" type="text">
<br>
<input id="getFolderButton" type="button" onclick="getFolderButtonClick()" value="Get Folder">
<script>
function getFolderButtonClick() {
try {
google.script.run.withSuccessHandler(
function(folder) {
document.getElementById("uploadParentFolderId").value = folder;
}
).getFolder();
}
catch(err) {
alert(err);
}
}
</script>
</body>
</html>
Code.gs
function getFolder() {
try {
let spread = SpreadsheetApp.getActiveSpreadsheet();
let file = DriveApp.getFileById(spread.getId());
let folders = file.getParents();
return folders.next().getId();
}
catch(err) {
throw "Error in test: "+err;
}
}
Reference
google.script.run.withSuccessHandler()
Another way to do this is via a printing scriptlet. You can use HTML templates which will output data from your server functions and print it to the HTML file.
Based on the script you found you can first change the declaration of the folder const on the forms.html file:
const uploadParentFolderId = <?=getParent()?>; // creates a folder inside of this folder
As explained in the docs, the <?= ... ?> tags indicate that the output from the getParent() function will be printed to the HTML file.
Then create getParent() on the Code.gs file to return the ID of the sheet's parent folder:
function getParent(){
var ss = SpreadsheetApp.getActiveSpreadsheet()
var id = ss.getId()
var parent = DriveApp.getFileById(id).getParents().next().getId()
return parent
}
Finally change the doGet() function on the Code.gs file to use a template instead of just printing the HTML file, this is so the <?=?> tags can be interpreted before outputting the page:
function doGet(e) {
return HtmlService.createTemplateFromFile('forms.html').evaluate();
}
I just modified this from the script and was able to create the new folder in the same location as the Spreadsheet.
Reference:
HTML Templates

How to move JavaScript code with Servlets into external file?

I have some JavaScript code with Servlets code, I want to move all of them (between ) to external js file, but it doesn't work, what can I do? How to modify my code if only part of JavaScript can move to external file.
<script language="JavaScript" type="text/JavaScript">
var sel = document.getElementById('sel');
var selList = [];
<%
String key = "";
String text = "";
for(int i = 0; i < master.size(); i++) {
Map option = (Map) master.get(i);
key = (String) option.get("Code");
text = key + " " + (String) option.get("NAME");
%>
selList.push({
key: "<%=key%>",
text: "<%=text%>"
});
<%
}
%>
</script>
Here two options:
1-by not using ajax
external.js
var images;
function renderImages(){
//do things for showing images here.
//images variable has images data as JSON (i suggest you this way) so you can easily iterate over list and render it.
}
jsp
<html>
<head>
<script type="text/javascript" src="external.js"></script>
<script>
images = "<%=request.getAttribute("imageDataAsJSON")%>"; //here i assume you populate request variable with your image data in JSON format. Be careful about parse errors due to ' and ".
</script>
</head>
<body>
<script>
renderImages();
</script>
</body>
</html>
2-by using ajax (you can seperate client side logic into external js code and populate data into it by doing ajax calls to server side.)
external.js
function renderImages(){
//do ajax to your servlet which returns image data as JSON.
//iterate over image data and render your html elements accordingly.
}
jsp
<html>
<head>
<script type="text/javascript" src="external.js"></script>
</head>
<body>
</body>
</html>

Scrape html with js

I'm trying to get the html of www.soccerway.com. In particular this:
that have the label-wrapper class I also tried with: select.nav-select but I can't get any content. What I did is:
1) Created a php filed called grabber.php, this file have this code:
<?php echo file_get_contents($_GET['url']); ?>
2) Created a index.html file with this content:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>test</title>
</head>
<body>
<div id="response"></div>
</body>
<script>
$(function(){
var contentURI= 'http://soccerway.com';
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
});
var LI = document.querySelectorAll(".list li");
var result = {};
for(var i=0; i<LI.length; i++){
var el = LI[i];
var elData = el.dataset.value;
if(elData) result[el.innerHTML] = elData; // Only if element has data-value attr
}
console.log( result );
</script>
</html>
in the div there is no content grabbed, I tested my js code for get all the link and working but I've inserted the html page manually.
I see a couple issues here.
var contentURI= 'http:/soccerway.com #label-wrapper';
You're missing the second slash in http://, and you're passing a URL with a space and an ID to file_get_contents. You'll want this instead:
var contentURI = 'http://soccerway.com/';
and then you'll need to parse out the item you're interested in from the resulting HTML.
The #label-wrapper needs to be in the jQuery load() call, not the file_get_contents, and the contentURI variable needs to be properly escaped with encodeURIComponent:
$('#response').load('grabber.php?url='+ encodeURIComponent(contentURI) + ' #label-wrapper');
Your code also contains a massive vulnerability that's potentially very dangerous, as it allows anyone to access grabber.php with a url value that's a file location on your server. This could compromise your database password or other sensitive data on the server.

Can't pass a javascript variable to a php tag

I want to display a javascript variable in the tag in the HTML page but it doesn't appear when I click the button. Can anyone tell me what I'm doing wrong?
HTML
<button name = "presser">go </button>
<p id = "display"></p>
<script type ="text/javascript" src ="jquery.js"></script>
<script type ="text/javascript" src = "processor_file.js"></script>
Javascript
$(":button").click(function(){
$.get("middleman.php", {theword: "happen"},function(data,status){
$.getElementById("display").innerHTML = data;
});
});
PHP code from middleman.php
<?php
if(isset($_GET["theword"])){
$token = $_GET["theword"];
echo substr($token, 1, 3);
}
?>
The word is successfully passed to the javascript page from the php page but when I try to display it through the <p> tag, nothing happens.
You are mixing vanilla js and jquery, you should do as follows:
$(":button").click(function(){
$.get("middleman.php", {theword: "happen"},function(data,status){
$("#display").html(data);
});
});
$.getElementById should be document.getElementById. Or use the jQuery function
$("#display").html(data);

how to insert javascript code via jquery?

<div id="example">
</div>
<script type="text/javascript">
function insert() {
var data = '<script type="text/javascript"> function test() { a = 5; }<\/script>';
$("#example").append(data);
}
function get() {
var content = $("#example").html();
alert(content);
}
</script>
INSERT
GET
</body>
</html>
what i want to do:
when i click on insert, i want to insert this code into example div:
<script type="text/javascript"> function test() { a = 5; }<\/script>
when i click on get, i want to get that code, which i inserted there.
but when i click on insert, and then on get, there's no code.. where is problem ? thanks
According to your comment to Adam Bellaire, you want the script tag to display as normal text. What you are looking to do is encode the text with HTML entities, this will prevent the browser from processing it as normal HTML.
var enc = $('<div/>').text('<script type="text/javascript"> function test() { a = 5; }<\/script>').html();
$("#example").append(enc);
This works:
function insert() {
var data = '<script type="text/javascript"> function test() { a = 5; }<\/script>';
$('#example').text(data);
}
function get() {
var content = $('#example').text();
alert(content);
}
Are you checking for the code by browsing the live version of the DOM, using a tool like Firebug? If you are expecting to see your code rendered in your regular browser window, you won't, because the script tags are actually parsed when they are inserted, and script tags aren't visible elements in an HTML page.

Categories