Good afternoon,
I'm new to google script and would like to know how I can get data from an HTML form and put it in a document. I need to put the data into the cube in the title of a file that is created at the click of a button. Thank you.
The following project might be helpful for your problem.
https://github.com/terrywbrady/PlainTextCSV_GoogleAppsScript
In this code, a Google App Script project is deployed as a web app.
The doGet() method returns an html page with a form.
function doGet() {
var html = HtmlService.createHtmlOutputFromFile('Index')
.setSandboxMode(HtmlService.SandboxMode.IFRAME);
return html;
}
The html page has a submit function that invokes the following function.
function handleFormPost(formObject) {
jQuery("input:button").attr("disabled",true);
google.script.run.withSuccessHandler(updateOutput)
.withFailureHandler(fail).doTextPost(formObject);
}
This function calls the doTextPost() method in the App Script code.
function doTextPost(req) {
var name = getParam(req, "name", "");
var folderid = getParam(req, "folderid", "");
var delim = getParam(req, "delim", ",");
var resp = createPlainTextSpreadsheet(req.data, name, folderid, delim);
return JSON.stringify(resp);
}
The success handler defined on the html page processes the JSON data returned from this function.
function updateOutput(data) {
var resp = jQuery.parseJSON(data);
document.getElementById("output").innerHTML="<a href='"+resp.url+"'>"+resp.name+"</a> created on Google Drive";
}
Related
I am building a Wordpress site, and using AJAX to load in subsequent pages when the user navigates, so that page transitions are nicely animated.
By default, if you load and inject a page with an embedded Ninja Form, the form simply does not display. There is very little information out there on how to achieve this. I hoped there would be an official out of the box way to get this working, but there doesn't appear to be.
What steps need to be taken in order to get the form to display on the page, when the form has been dynamically loaded with AJAX?
I have experimented with some completely undocumented code samples, and managed to figure it out, along with a few necessary tweaks and additions. I thought I'd share here in case anyone else has difficulty with this.
Step 1. Enqueue necessary JS and CSS
Add the following to your functions.php, because Ninja Forms relies on backbone js, and needs css, which won't be loaded if your initial landing page does not already have a form on it.
add_action('wp_enqueue_scripts', function () {
// enqueue ninja forms css, including for any ninja forms addons
wp_enqueue_style('nf-display', content_url('/plugins/ninja-forms/assets/css/display-structure.css'), ['dashicons'], core_dev_version(''));
wp_enqueue_style('nf-layout-front-end', content_url('/plugins/ninja-forms-style/layouts/assets/css/display-structure.css'), ['nf-display'], core_dev_version(''));
// make sure that backbone is enqueued on the page, as ninja forms relies on this
wp_enqueue_script('backbone');
}, 100);
.
Step 2. Add an AJAX function that returns the form data
You shouldn't need to edit this, just add it to your functions.php. The javascript we use in step 3 will make its own AJAX call to request some form data in a very specific format.
add_action('init', function () {
// if this is not an AJAX form request, return
if (! isset($_REQUEST[ 'async_form' ])) {
return;
}
// clear default loaded scripts.
global $wp_scripts;
unset($wp_scripts->registered);
// get the requested form id
$form_id = absint($_REQUEST['async_form']);
// retrieve the requested form
ob_start();
$form = do_shortcode("[ninja_forms id='{$form_id}']");
ob_get_clean();
// output the requested form on the page
ob_start();
NF_Display_Render::output_templates();
$templates = ob_get_clean();
$response = [
'form' => $form,
'scripts' => $wp_scripts->registered,
'templates' => $templates
];
echo json_encode($response);
// die, because we don't want anything else to be returned
die();
});
.
Step 3. Add JS helper functions to your landing page
This simply adds some helpful JS code into your site.
You can add this to functions.php as is, or include it in a separate JS file.
This is what we will use to load and initialise the form we want.
add_action('wp_footer', function () {
// adds a script to the footer
?>
<script type="text/javascript">
var NinjaFormsAsyncForm = function(formID, targetContainer) {
this.formID = formID;
this.targetContainer = targetContainer;
this.formHTML;
this.formTemplates;
this.formScripts;
this.fetch = function(callback) {
jQuery.post('/', { async_form: this.formID }, this.fetchHandler.bind(this))
.then(callback);
}
this.fetchHandler = function(response) {
response = JSON.parse( response );
window.nfFrontEnd = window.nfFrontEnd || response.nfFrontEnd;
window.nfi18n = window.nfi18n || response.nfi18n || {};
this.formHTML = response.form;
this.formTemplates = response.templates;
this.formScripts = response.scripts;
}
this.load = function() {
this.loadFormHTML(this.formHTML, this.targetContainer);
this.loadTemplates(this.formTemplates);
this.loadScripts(this.formScripts);
}
this.loadFormHTML = function(form, targetContainer) {
jQuery(targetContainer).append( form );
}
this.loadTemplates = function(templates) {
document.body.innerHTML += templates;
}
this.loadScripts = function(scripts) {
jQuery.each( scripts, function( nfScript ){
var script = document.createElement('script');
// note that eval() can be dangerous to use - do your research
eval( scripts[nfScript].extra.data );
window.nfFrontEnd = window.nfFrontEnd || nfFrontEnd;
script.setAttribute('src',scripts[nfScript].src);
var appendChild = document.head.appendChild(script);
});
}
this.remove = function() {
jQuery(this.targetContainer).empty();
}
}
</script>
<?php
}, 100);
.
Step 4. Initialise the form after you AJAX in your page
I can't tell you how to AJAX in your pages - that's a whole other topic for you to figure out.
But, once you have loaded your page content with included Ninja Form, and once that has successfully been on the page, now you need to initialise the form.
This uses the javascript helper (step 3), which in turn calls the php helper (step 2), and finally displays the form on your page!
You'll need to know the ID of the form that's been injected. My tactic was to include this as a data-attribute in my page markup.
var form_id = 1;
var asyncForm = new NinjaFormsAsyncForm(form_id, '.ninja-forms-dynamic');
asyncForm.fetch(function () {
asyncForm.load();
});
And that's about all there is to it!
Hopefully this may save others the time and effort of figuring all of this out.
I have a trigger set up in Google Sheets so a URL is automatically opened in a new browser window. This works if the URL is hardcoded. I want the URL to be a variable. How do I pass the URL variable from Apps Script to HTML script? I'm a novice coder so please explain like I'm 5.
This function works if the URL is text like 'https://www.google.com'
function openMap() {
var maplink = SpreadsheetApp.getActiveSheet().getRange("B2").getValues();
var js = "<script>window.open('https://www.google.com', '_blank', 'width=800, height=600');google.script.host.close();</script>";
var html = HtmlService.createHtmlOutput(js)
.setHeight(10)
.setWidth(100);
SpreadsheetApp.getUi().showModalDialog(html, 'Now loading.');
}
This function does not if the URL is a variable (I checked the maplink value and its a valid URL)
function openMap() {
var maplink = SpreadsheetApp.getActiveSheet().getRange("B2").getValues();
var js = "<script>window.open('maplink', '_blank', 'width=800, height=600');google.script.host.close();</script>";
var html = HtmlService.createHtmlOutput(js)
.setHeight(10)
.setWidth(100);
SpreadsheetApp.getUi().showModalDialog(html, 'Now loading.');
}
You can join strings in the following manner:
...
var url = 'https://www.google.com';
var js = "<script>window.open('" + url + "', '_blank', 'width=800, height=600');google.script.host.close();</script>";
...
Basically
you close the first part of your hardcoded string by closing the quotes
add the dynamical variabl with +
continue the hardcoded string by appending the second part with + and opening the quotes again
I hope this is clear!
I'm trying to put together a picker in google sheets.
Once a file has been uploaded to google drive, I want the url to be posted in the current cell in the spreadsheet.
This is my pickerCallback located in an html file:
var message;
function pickerCallback(data) {
var action = data[google.picker.Response.ACTION];
if (action == google.picker.Action.PICKED) {
var doc = data[google.picker.Response.DOCUMENTS][0];
var id = 'https://drive.google.com/open?id=' + doc[google.picker.Document.ID];
google.script.run.accessSpreadsheet();
} message = id;
document.getElementById('result').innerHTML = message;
}
This returns the url in the picker dialog box.
My accessSpreadsheet function looks like this and is located in a google script file:
function accessSpreadsheet() {
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var currentCell = sheet.getCurrentCell();
currentCell.setValue(message);
return spreadsheet;
}
The function runs but it cannot define message. Is there a way to access the variable defined in the function in the html file from the google scripts function? Or is there another better way to do this?
Solution:
Pass the string id from client side to server.
Snippets:
google.script.run.accessSpreadsheet(id);
function accessSpreadsheet(id) {
currentCell.setValue(id);
Reference:
Client-Server communication
I want to load the PDF file dynamically and show on browser. PDF file is created on the fly when user clicks on button and the filename has timestamp in it. So i cannot give the PDF filename in the html code as shown below as it changes based on the timestamp(PDF file name is given along with the timestamp when it was created as shown in below spring controller).
Below is the code.
html code:
<div ng-controller="generatePDFController">
<button ng-click="generatePDF()">Re-Generate PDF</button>
<object data="C:/allFiles/PDFFiles/spreadDetails.pdf" type="application/pdf" width="100%" height="100%">
<iframe src="C:/allFiles/PDFFiles/spreadDetails.pdf" width="100%" height="100%" style="border: none;">
This browser does not support PDFs.
Download PDF
</iframe>
</object>
</div>
js code:
app.controller('generatePDFController', function($scope, MyService) {
$scope.generatePDF = function() {
MyService.createPDF().then(
function(response) {
$scope.pdf = response;
},
function(errResponse) {
});
}
});
//service call
_myService.createPDF = function() {
var deferred = $q.defer();
var repUrl = sURL + '/allDataGeneration/generatePDF.form';
$http.get(repUrl)
.then(
function(response) {
deferred.resolve(response.data);
},
function(errResponse) {});
return deferred.promise;
}
spring controller:
#RequestMapping(value = "/generatePDF", method = RequestMethod.GET)
public# ResponseBody List < MyDTO > generatePDF() {
List < MyDTO > response = service.getAllData();
//create PDF and write the response in it
createPDFFile(response);
return response;
}
void createPDFFile(List < MyDTO > res) {
String FILE_PATH = "C:\\allFiles\\PDFFiles\\spreadDetails";
String FILE_EXTENSION = "pdf";
DateFormat df = new SimpleDateFormat("MM-dd-yyyy hh-mm-ssa");
String filename = null;
try {
filename = FILE_PATH + df.format(new Date()) + "." + FILE_EXTENSION;
} catch (Exception e) {
e.printStackTrace();
}
File file = new File(filename);
System.out.println("-----filename------------ " + filename); //PDF file is created successfully
//spreadDetails07-13-2017 02-59-51PM ,when user clicks on GeneratePDF in UI, it hits this controller and generates the PDF
//logic to write the data inside PDF file
}
The above shown code is the complete flow of my sample application. Now when user clicks on Re-Generate PDF button, it comes to above mentioned spring controller creates a file with timestamp and writes the data in it.How to pass the newly created pdf filename to the html code <object data="C:/allFiles/PDFFiles/spreadDetails.pdf" .. so that when pdf file is created it dynamically loads and show on UI.
---EDITED---
Please see the above edited code. createPDF(List<MyDTO>) is a new method in which i'm creating a pdf file and writing the content. I will be reusing this method.
Try to follow these steps :
Change the signature of the Java method generatePDF() in order to return a String representing the name of your file. This gives you the possibility to pass the name of the file to your JavaScript ;
In your controller, do $scope.pdfName = response. This way the name of the file is store the variable $scope.pdfName ;
Last step, replace <object data="C:/allFiles/PDFFiles/spreadDetails.pdf" ...> by <object data="{$scope.pdfName}" ...>
This should work.
Marine
EDIT given your own edit :
Your method generatePdf() is incorrect : you wrote that it must return a List<MyDto> but the keyword return is nowhere.
Do you really need to return he object List<MyDto> ? In any case, you need to return the name of the file to be able to use it in your JavaScript. So, you have two solutions : either this method only returns a String representing the name of the PDF, or it returns an object with two fields, one String and one List<MyDto>. In this second cas, you will need to do
$scope.pdfName = response.fieldContainingTheNameOfTheFile.
I'm using a script to extract data from google search console in a sheet.
I built a sidebar to chose on which website the user want to analyse his data.
For that i have a function that can list all sites link to the google account, but i have an error when i try to execute this function in my html file.
I use withSuccessHandler(function) method which sets a callback function to run if the server-side function returns successfully. (i have a OAuth2.0.gs file where is my getService function.
The error is "service.hasAccess is not a function at listAccountSites" where listAccountSites is my function. Here's an extract of my html file:
<script src="OAuth2.0.gs"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script>
$(function() {
var liste = google.script.run.withSuccessHandler(listAccountSites)
.getService();
console.log(liste);
});
function listAccountSites(service){
if (service.hasAccess()) {
var apiURL = "https://www.googleapis.com/webmasters/v3/sites";
var headers = {
"Authorization": "Bearer " + getService().getAccessToken()
};
var options = {
"headers": headers,
"method" : "GET",
"muteHttpExceptions": true
};
var response = UrlFetchApp.fetch(apiURL, options);
var json = JSON.parse(response.getContentText());
Logger.log(json)
console.log('if')
var URLs = []
for (var i in json.siteEntry) {
URLs.push([json.siteEntry[i].siteUrl, json.siteEntry[i].permissionLevel]);
}
/*
newdoc.getRange(1,1).setValue('Sites');
newdoc.getRange(1,3).setValue('URL du site à analyser');
newdoc.getRange(2,1,URLs.length,1).setValues(URLs);
*/
console.log(URLs);
} else {
console.log('else')
var authorizationUrl = service.getAuthorizationUrl();
Logger.log('Open the following URL and re-run the script: %s', authorizationUrl);
Browser.msgBox('Open the following URL and re-run the script: ' + authorizationUrl);
}
return URLs;
}
</script>
i found the solution.
Jquery is useless here, you just have to use google.script.run.yourfunction() to run your gs. function on your html sidebar.