InsideDarkWeb.com

Only the else condition works in my google apps script Twilio Fax sending web app

I’m having an issue with my If statement.

Basically I set up a fax app with Twilio and Google apps script.

I give the user a choice to upload a document or send out one that stored on my Google drive.
If I upload a file it works. But if I check the checkbox to send a pre-set document, which I’m trying to accomplish by using the If statement it doesn’t send.

I troubleshooted, and found that the If statements is getting a TRUE and FALSE value.

I think the problem is that when there is no file passed into the function it doesn’t work. The thing is I’m avoiding the file by the If statement so why is it not working.

Below is my HTML file and server side apps script.

Any suggestions?

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('form.html');

}

function uploadFiles(blob, name, number, test) {
 
       //get destination number
  var num = number;
  var prefix = "+1";
  var removeDashes = num.replace(/-/g,"");
  var fullNumber = prefix + removeDashes;
  
  var output;
if (test){
output = "APPLICATION SENT!";
}else{
output = "FAX SENT!";
}
  
    var url;
  if (test) {
  var appl = DriveApp.getFileById('xxxxxxxxx');
  var appurl = appl.getDownloadUrl();
    url = appurl;  

  } else {
    var folder = DriveApp.getFolderById('xxxxxxxxxxx');
    var blob = blob.split(",");
    var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf');
    var fileName = blob.setName(name).getName();
    var file = folder.createFile(blob); 
  
      //allow access to Twilio
  file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  
  //get file url
  var id = file.getId();
  var getfile = DriveApp.getFileById(id);
  var getnewurl = getfile.getDownloadUrl();
   var url = getnewurl;
 }
  
   //send fax
  var faxUrl = "https://fax.twilio.com/v1/Faxes";
         
        var payload = {
          "From" : "+1888888888",
          "To": fullNumber,
          "MediaUrl" : url,
          "Method" : "POST",
        };
        
        var options = {
          "method" : "post",
          "payload" : payload
        };
        
        options.headers = {    
          "Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxxxxxxxxxx:xxxxxxxxxxxxxxxxxxxxxxx")
        };
        UrlFetchApp.fetch(faxUrl, options);
  
  return "succes" + output;
}

Here is the HTML file: (I removed the <style> in order to shorten)

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
    <script>
      // Prevent forms from submitting.
      function preventFormSubmit() {
        var forms = document.querySelectorAll('form');
        for (var i = 0; i < forms.length; i++) {
          forms[i].addEventListener('submit', function(event) {
            event.preventDefault();
          });
        }
      }
      window.addEventListener('load', preventFormSubmit);

function upload() {
var file = document.getElementsByName('myFile')[0].files[0];
var number = document.getElementsByName('Pnumber')[0].value;
var test = document.getElementsByName("entered")[0].checked;
var reader = new FileReader();
reader.onload = function (e) {
var content = reader.result;

google.script.run.withSuccessHandler(fileUploaded).uploadFiles(content, file.name, number, test);

return false;
}
reader.readAsDataURL(file);
}   

function fileUploaded(status) {
document.getElementById("myForm").reset();
document.getElementById('output').innerHTML = status;
}    
</script>
</head>
<body>
<div align="center">
<h1 align="center" style="color:darkblue">FAX APP</h1>

<h2 align="center">SEND OUTGOING FAX</h2>
<hr>
<form id="myForm" align="center">

<label for="pdf">Choose a PDF file to upload -- <b>OR</b>-- Check "SEND APPLICATION" </label>
<br>
<input id="pdf" type="file" name="myFile" >
<br><br>

<input type="checkbox" style="width:25px ; height:25px" name="entered">
<label for="entered" style="font-size:30px" >  SEND APPLICATION</label>

<br><br>
<label for="phonenumber">Enter Destination Number</label>
<br>
<input id="phonenumber" type="text" name="Pnumber" placeholder="Phone Number" >
<br>
<input type="submit" value="SEND FAX" onclick="upload()" >
</form>
<p><b>FAX DELIVERY STATUS:</b></p>
<div id="output"align="center"><b></b></div>
<br>
<a href="https://drive.google.com/drive/folders/xxxxxxxxxxxxxxxxxxx?usp=sharing"
target="_blank">SENT FAX DOCUMENTS</a>
</div>

</body>
</html>

BELOW IS THE NOW WORKING CODE OF GOOGLE SCRIPT SIDE AND HTML
THANKS TO @Tanaike’s HELP

CURRENT GOOGLE SCRIPT SIDE CODE:

function doGet(e) {
  return HtmlService.createHtmlOutputFromFile('form.html');

}

function uploadFiles(blob, name, number, test) {
 
       //get destination number
  var num = number;
  var prefix = "+1";
  var removeDashes = num.replace(/-/g,"");
  var fullNumber = prefix + removeDashes;
  
  var output;
if (test){
output = "APPLICATION SENT!";
}else{
output = "FAX SENT!";
}
  
  var url;
if (test) {
  var appl = DriveApp.getFileById('xxxxxxxxxxxxxxxxxxxxxxx');
  var appurl = appl.getDownloadUrl();
    url = appurl;  
  } else {
    var folder = DriveApp.getFolderById('xxxxxxxxxxxxxxxxxxxxxxxxxxx');

    var blob = blob.split(",");
    var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf', name);
    
    var file = folder.createFile(blob); 
  
      //allow access to Twilio
  file.setSharing(DriveApp.Access.ANYONE_WITH_LINK, DriveApp.Permission.VIEW);
  
  //get file url
  var id = file.getId();
  var getfile = DriveApp.getFileById(id);
  var getnewurl = getfile.getDownloadUrl();
   url = getnewurl;
 }
  
    
   
   //send fax
  var faxUrl = "https://fax.twilio.com/v1/Faxes";
         
        var payload = {
          "From" : "+188888888888",
          "To": fullNumber,
          "MediaUrl" : url,
          "Method" : "POST",
        };
        
        var options = {
          "method" : "post",
          "payload" : payload
        };
        
        options.headers = {    
          "Authorization" : "Basic " + Utilities.base64Encode("ACxxxxxxxxxxxxxxxxxx:xxxxxxxxxxxxxxxxxxx")
        };
        UrlFetchApp.fetch(faxUrl, options);
  
  return "Success - " + output;
}

CURRENT HTML SIDE CODE:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">

    <script>
      // Prevent forms from submitting.
      function preventFormSubmit() {
        var forms = document.querySelectorAll('form');
        for (var i = 0; i < forms.length; i++) {
          forms[i].addEventListener('submit', function(event) {
            event.preventDefault();
          });
        }
      }
      window.addEventListener('load', preventFormSubmit);

function upload() {
  var file = document.getElementsByName('myFile')[0].files[0];
  var number = document.getElementsByName('Pnumber')[0].value;
  var test = document.getElementsByName("entered")[0].checked;
  
        if(!test){
            var reader = new FileReader();
          reader.onload = function (e) {
            var content = reader.result;
        
        google.script.run.withSuccessHandler(fileUploaded).uploadFiles(content, file.name, number, null);
        
        return false;
        }
        
        reader.readAsDataURL(file);  
        
        }else{
        google.script.run.withSuccessHandler(fileUploaded).uploadFiles(null, null, number, test);
        
        return false;
        }
}
function fileUploaded(status) {
document.getElementById("myForm").reset();
document.getElementById('output').innerHTML = status; 
}
</script>
</head>






<body>
<div align="center">
<h1 align="center" style="color:darkblue">FAX APP</h1>

<h2 align="center">SEND OUTGOING FAX</h2>
<hr>
<form id="myForm" align="center">

<label for="pdf">Choose a PDF file to upload -- <b>OR</b>-- Check "SEND APPLICATION" </label>
<br>
<input id="pdf" type="file" name="myFile" >
<br><br>

<input type="checkbox" style="width:25px ; height:25px" name="entered">
<label for="entered" style="font-size:30px" >  SEND APPLICATION</label>

<br><br>
<label for="phonenumber">Enter Destination Number</label>
<br>
<input id="phonenumber" type="text" name="Pnumber" placeholder="Phone Number" >
<br>
<input type="submit" value="SEND FAX" onclick="upload()" >
</form>
<p><b>FAX DELIVERY STATUS:</b></p>
<div id="output"align="center"><b></b></div>
<br>
<a href="https://drive.google.com/drive/folders/xxxxxxxxxxxxxxxx?usp=sharing"
target="_blank">SENT FAX DOCUMENTS</a>
</div>

</body>
</html>

Stack Overflow Asked on November 18, 2021

1 Answers

One Answer

I believe your goal as follows.

  • You want to remove the error when SEND APPLICATION is checked without selecting a file.

Modification points:

  • When the file is not selected, an error occurs at FileReader because file is undefined. I think that this might be the reason of your issue.
  • In this case, I would like to propose the function upload() at Javascript side as follows.
    • if (file && !test) {}else{} is used. By this,
      • When the file is selected AND SEND APPLICATION is not checked, the selected file is used.
      • When the file is not selected OR SEND APPLICATION is checked, the file of var appl = DriveApp.getFileById('xxxxxxxxx') is used.
    • About this, please modify the if statement for your actual situation.

Modified script:

When your script is modified, please modify upload() at Javascript side as follows.

function upload() {
  var file = document.getElementsByName('myFile')[0].files[0];
  var number = document.getElementsByName('Pnumber')[0].value;
  var test = document.getElementsByName("entered")[0].checked;
  
  // I modified below script.
  if (file && !test) {
    var reader = new FileReader();
    reader.onload = function(e) {
      var content = reader.result;
      google.script.run.withSuccessHandler(fileUploaded).uploadFiles(content, file.name, number, test);
      return false;
    }
    reader.readAsDataURL(file);
  } else {
    google.script.run.withSuccessHandler(fileUploaded).uploadFiles(null, null, number, test);
  }
}
  • In this modification, Google Apps Script side is not modified.

Added:

I think that your current issue is due to that you changed Google Apps Script from the script in the initial question. In the current script, name is removed at Google Apps Script and Javascript. By this, an error occurs at createFile. Please use name as follows.

From:

var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf');

To:

var blob = Utilities.newBlob(Utilities.base64Decode(blob[1]), 'application/pdf', "sample");
  • In this case, the filename is a temploral. So you can use various name like "sample", "temp" and so on.

  • And when you modified the script of Web Apps, please redeploy the Web Apps as new version. By this, the latest script is reflected to the Web Apps. Please be careful this.

  • And in your current script, if (!test) { is used. In this case, when the button is cliced without selecting file and cheking the checkbox, an error occrurs. Please be careful this.

Answered by Tanaike on November 18, 2021

Add your own answers!

Related Questions

Have the class as value in a dictionary

4  Asked on January 20, 2021 by bows

     

Add Speed to WASD Controls for A-Frame

2  Asked on January 19, 2021 by dionoh

   

Calculate the address of the subnet

2  Asked on January 19, 2021 by kingvince

 

IBM MQ Client running under Windows Docker

2  Asked on January 19, 2021 by lumberjack

   

Is clang-11’s invocation of headers via -fcoroutines flag?

0  Asked on January 18, 2021 by jerry-ajay

       

Operational Error connecting to SQL Server through Python3.7

1  Asked on January 18, 2021 by christopher-ell

     

Logo is not changing

1  Asked on January 18, 2021 by paul-ocarde

 

Android rdate exception

0  Asked on January 18, 2021 by elior-cohen

 

Ask a Question

Get help from others!

© 2021 InsideDarkWeb.com. All rights reserved.