Is there a way to get a QR code image with Google Apps Script using the POST method of the Google Charts API? - post

I am using a Google Script to generate tickets to an event, and the ticket includes a QR code which goes to a pre-filled Google Form link. Since it's pre-filled, the string is quite long, and the Google Charts API for creating QR codes will not accept a string of text that long using a GET request, but I can't find any documentation of how to code the POST request into Apps Script. How do I generate a POST request in Apps Script that will return an image of the QR code which I can then insert into the document?
I already tried the GET request, and it truncates the URL before encoding it into a QR code. That gets me to the Google Form, but not the pre-filled version that the link generates (actually pretty smart on Google's part to have it truncate the string in a place that still gives a usable URL, but that's for another day...)
I have also tried the HtmlService to render the QR code using the POST method with the Charts API in an HTML form that automatically submits on the loading of that HTML. If I use showSidebar(), this will open the image in a new tab, but I haven't figured out how to return that image so that it can be inserted into the document.
I've also tried creating a blob with the HTML and then saving the blob as a PNG, but from the research I've done, the .getAs() method doesn't render images when converting the HTML.
The renderQR function:
function renderQR(inputUrl) {
var html = HtmlService.createTemplateFromFile('QREncode.html');
html.url = inputUrl;
var rendered = html.evaluate().setSandboxMode(HtmlService.SandboxMode.IFRAME)
.setHeight(300)
.setWidth(300);
return rendered;
}
The QREncode.html file:
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script type='application/javascript'>
// Send the POST when the page is loaded,
// which will replace this whole page with the retrieved chart.
function loadGraph() {
var frm = document.getElementById('post_form');
if (frm) {
frm.submit();
}
}
</script>
</head>
<body onload="loadGraph()">
<form action='https://chart.googleapis.com/chart' method='POST' id='post_form'>
<input type='hidden' name='cht' value='qr' />
<input type='hidden' name='chl' value='<?= url ?>' />
<input type='hidden' name='chs' value='300x300' />
<input type='submit'/>
</form>
</body>
</html>
When I treat the return from the renderQR() function as an image, Apps script gives an error saying that it is "Invalid image data", which makes sense -- but how do I convert it into an image, or is there a better or simpler way I could be doing this?

You need to get the qr code in the Apps Script, not in the browser:
var imageData = UrlFetchApp.fetch('https://chart.googleapis.com/chart', {
'method' : 'post',
'payload' : {
'cht': 'qr',
'chl': 'https://google.com',
'chs': '300x300'
}}).getContent();

For those looking for a formula solution (without Apps Script)
Reference: https://www.benlcollins.com/spreadsheets/qr-codes-in-google-sheets/
Solution:
=IMAGE("https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl="&ENCODEURL(A1))

Related

How can I show a confirmation page before saving an image with carrierwave in rails?

I have a form in which a user may upload an image, and I'm using carrierwave to process it. Currently, the user makes a post by filling out a form and clicking submit. This takes the user to a confirmation page where all the information is displayed once more after going through rails validations, including a preview of the image, before actually creating the post. I need to display the image on this page before actually saving and sending it into to S3.
#topic_picture_uploader = TopicPictureUploader.new
#topic_picture_uploader.cache!(params[:topic_picture])
I tried to cache it like this, but trying to access anything only returns nil. How can I simply display the image before saving it to a model?
No need to submit the page, Just have the preview button on the form and on clicking of it show whatever the data you want to show and along with it show the submit button as well to complete the post.Please take a look at the sample JS code below:
function readURL(input) {
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$('#blah').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
$("#imgInp").change(function(){
readURL(this);
});
and the associated HTML:
<form id="form1" runat="server">
<input type='file' id="imgInp" />
<img id="blah" src="#" alt="your image" />
</form>

YouTube API Academy

I just completed the YouTube API tutorials on Codecademy and successfully managed to display results relating to a given 'q' value in the console window provided using the following code:
// Helper function to display JavaScript value on HTML page.
function showResponse(response) {
var responseString = JSON.stringify(response, '', 2);
document.getElementById('response').innerHTML += responseString;
}
// Called automatically when JavaScript client library is loaded.
function onClientLoad() {
gapi.client.load('youtube', 'v3', onYouTubeApiLoad);
}
// Called automatically when YouTube API interface is loaded (see line 9).
function onYouTubeApiLoad() {
// This API key is intended for use only in this lesson.
// See http://goo.gl/PdPA1 to get a key for your own applications.
gapi.client.setApiKey('AIzaSyCR5In4DZaTP6IEZQ0r1JceuvluJRzQNLE');
search();
}
function search() {
// Use the JavaScript client library to create a search.list() API call.
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: "Hello",
});
// Send the request to the API server,
// and invoke onSearchRepsonse() with the response.
request.execute(onSearchResponse);
}
// Called automatically with the response of the YouTube API request.
function onSearchResponse(response) {
showResponse(response);
}
and:
<!DOCTYPE html>
<html>
<head>
<script src="search.js" type="text/javascript"></script>
<script src="https://apis.google.com/js/client.js?onload=onClientLoad" type="text/javascript"></script>
</head>
<body>
<pre id="response"></pre>
</body>
</html>
The problem I am having now is that I have taken this code and put it into my own local files with the intention of furthering my understanding and manipulating it work in a way which suits me, however it just returns a blank page. I assume that it works on Codecademy because they use a particular environment and the code used perhaps only works within that environment, I am surprised they wouldn't provide information on what changes would be required to use this outside of their given environment and was hoping someone could shed some light on this? Perhaps I am altogether wrong, if so, any insight would be appreciated.
Browser Console Output:
Failed to execute 'postMessage' on 'DOMWindow': The target origin provided ('file://') does not match the recipient window's origin ('null').
I also had the same problem but it was resolved when I used Xampp. What you have to do is install xampp on your machine and then locate its directory. After You will find a folder named "htdocs". Just move your folder containing both js and HTML file into this folder. Now you have to open Xampp Control Panel and click on start button for both - Apache and SQL server. Now open your browser and type in the URL:
http://localhost/"(Your htdocs directory name containing both of your pages)"
After this, click on .html file and you are done.

How can I do a multipart Post in Dart / AngularDart

I've got a REST api which assumes a multipartfile in the a post method.
Is there any way to do this kind of posts in Dart / AngularDart because all the solutions I've found so far are not working.
I've tried to use the http://dart-gde.github.io/dart-google-oauth2-library/multipart_file/MultipartFile.html solution, but it is not working in the browser because dart.io is not supported there.
My question is about the client side part directly from the browser. The serverside, which is written in Java can handle the post.
If you need multipart for file upload, all you have to do is send a FormData object using the HttpRequest class. Example:
import "dart:html";
...
var fileData; //file data to be uploaded
var formData = new FormData();
formData.append("field", "value"); //normal form field
formData.appendBlob("data", fileData); //binary data
HttpRequest.request("/service-url", method: "POST", sendData: formData).then((req) {
...
});
Furthermore, if you need to allow the user to upload a file from his hard disk, you have to use a html form with an <input type="file"> tag. Example:
Html file:
<form id="myForm" action="/service-url" method="POST" enctype="multipart/form-data">
<input type="text" name="field"> <!-- normal field -->
<input type="file" name="fileData"> <!-- file field -->
</form>
dart file:
var formData = new FormData(querySelector("#myForm"));
HttpRequest.request("/service-url", method: "POST", sendData: formData).then((req) {
...
});
I know this was asked a long time ago, but I've just had the same problem and the fix for me is the following (based on luizmineo's answer):
Use formData.appendBlob("data", fileData);
Don't set an explicit Content-Type header. This will get Dart to calculate the boundary section of the form-data which is crucial.
I finally found a way to post it as a multi-part form:
void uploadFiles() {
var formData = new FormData(querySelector("#fileForm"));
HttpRequest.request("/sp/file", method: "POST", sendData: formData).then((req) {
print("OK");
});
}
is used in conjunction with
<form id="fileForm" action="/sp/file" method="POST">
<input type="file" #upload (change)="uploadFiles(upload.files)"
(dragenter)="upload.style.setProperty('border', '3px solid green')"
(drop)="upload.style.setProperty('border', '2px dotted gray')" class="uploadDropZone" name="toUpload"/>

Consume WCF Rest Service in ASP.net using jquery

I am trying to consume a wcf rest api in a asp.net project using jquery. for doing so i have done:
Created a WCF Rest service source code can be downloaded from here.
Created a ASP.Net project to consume that restAPI using jquery. source code here.
In ASP .Net project on the click of button I am trying to call a REST service. But every time I gets two issues:
calling var jsondata = JSON.stringify(request); in TestHTML5.js throws an error saying "Microsoft JScript runtime error: 'JSON' is undefined"
When I press ignore it continues towards WCF Rest API call but it always returns error (Not Found) function. Rest API never gets called.
Thanks for every one's help in advance.
ANSWER:
Solution and source link can be found on this link.
I have looked at the sample code you provided and the problem is that you are violating the same origin policy restriction. You cannot perform cross domain AJAX calls. In your example the service is hosted on http://localhost:35798 and the web application calling it on http://localhost:23590 which is not possible. You will have to host both the service and the calling application in the same ASP.NET project. You seem to have attempted to enable CORS on the client side using ($.support.cors = true;) but on your service doesn't support CORS.
Another issue saw with your calling page (TestHTML5.htm) is the fact that you have included jquery twice (once the minified and once the standard version) and you have included your script (TestHTML5.js) after jquery. You should fix your script references. And yet another issue is the following line <script type="text/javascript"/> which is invalid.
So start by fixing your markup (I have removed all the CSS noise you had in your markup in order to focus on the important parts):
<!DOCTYPE html>
<html dir="ltr" lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>SignUp Form</title>
<script type="text/javascript" src="../Scripts/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="../Scripts/TestHTML5.js"></script>
</head>
<body>
<button id="Send" onclick="testHTML5OnClick();">
Send Me ID!
</button>
</body>
</html>
and then in your TestHTML5.js you could also clean a little bit. For example your service is listening for the following url pattern json/{id} and accepting only GET verbs and you are attempting to use POST which is not possible. In addition to that you are attempting to use the JSON.stringify method which doesn't make any sense with the GET verb. You should simply send the id as part of the url portion as you defined in your service.
function testHTML5OnClick() {
var id = 5;
var url = "../RestServiceImpl.svc/json/" + id;
var type = 'GET';
callLoginService(url);
}
function callLoginService(url, type) {
$.ajax({
type: type,
url: url,
success: serviceSucceeded,
error: serviceFailed
});
}
function serviceSucceeded(result) {
alert(JSON.stringify(result));
}
function serviceFailed(result) {
alert('Service call failed: ' + result.status + '' + result.statusText);
}
Did u add this reference?
script type="text/javascript" src="../../json.js"></script>
I have same problem and search i get this and this result

File upload struts 2 with Ajax

I am uploading a file using struts 2 with jsp as front end, but I dont want to refresh the page after the file is uploaded, so i am using Ajax but with that I am not able to get the File object in action, it seems file upload needs form tag in jsp,and if I am submitting the form then the page gets refreshed.
I researched through the net but cant get many relevant results, it would be of great help if someone guides me through this, is there a way for it. Any help would really be appreciated.
Best regards
I suggest to use iframe for upload file instead of ajax,
Sample code for Upload Csv file using struts2 and iframe :
var file = $("#fileUpload").val();
if(file.indexOf(".") != -1 && file.substr(file.indexOf("."))==".csv"){
/* created IFrame For UPload file*/
var iframe = $('<iframe name="uploadIPAddressIFrame" id="uploadIPAddressIFrame" style="display: none" />');
$("body").append(iframe);
/* Set Form for submit iframe*/
var form = $('#ipPoolForm');
form.attr("action", "uploadCSVFile.do");
form.attr("target", "uploadIPAddressIFrame");
form.submit();
openDialog(title);
/* handle response of iframe */
$("#uploadIPAddressIFrame").load(function () {
response = $("#uploadIPAddressIFrame")[0].contentWindow.document.body.innerHTML;
$("#chkIPAddressDiv").html(response);
$("iframe#uploadIPAddressIFrame").remove();
});
After upload if you submit form then change target of form :
// Because of using iframe for upload set target value
$("#ipPoolForm").attr("target", "");

Resources