HtmlService.XFrameOptionsMode.ALLOWALL not working - google-apps-script

Having set the XframeOptionMode, the doPost still doesn't redirect:
var REDIRECT_URL = "https://stackoverflow.com";
function doGet() {
var template = HtmlService.createTemplateFromFile("CForm.html");
template.pubUrl = ScriptApp.getService().getUrl();
var html = template.evaluate();
html.setTitle('ABCD');
return HtmlService.createHtmlOutput(html).setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function doPost(e){
SendHtmlMail(e);
return redirect().setXFrameOptionsMode(HtmlService.XFrameOptionsMode.ALLOWALL);
}
function redirect() {
return HtmlService.createHtmlOutput(
"<script>window.top.location.href=\"" + REDIRECT_URL + "\";</script>"
);
}
The console error still remains
Refused to display 'https://script.google.com/macros/s/AKfycbyb3wh57wgW30KV8faQNqNXSDQ_zu8w3BR-_8kVwUbI/dev' in a frame because it set 'X-Frame-Options' to 'sameorigin'.
Relevant part of the HTML
<form class="container" id="main_form" method="post" action="<?= pubUrl ?>">
<div class="form-group">
<label>Business Name</label>
<input type="text" class="form-control" name="BusinessName" id="name" placeholder="Name of Upload" readonly>
</div>
<div class="form-group">
<label>Month and Year of Incorporation</label>
<input type="date" class="form-control" name="MonthandYearofIncorporation">
</div>
<input class="btn btn-md btn-success" type="submit" value="Apply for Carbon"/>
</form>

Though, manually pasting (hardcoding) the /exec url version of the script seems to alleviate the issue, I prefer not to.
I dropped the doPost and redirect function. Now my html now has script like:
<html>
    ...
    <body>
        ... First page ...
... Second page ...
        <form class="container d-none" id="main_form" method="post" action="<?pubUrl?>" onsubmit="submitter(this);">
   
            <div class="form-group">
                <label>Business Name</label>
                <input type="text" class="form-control" name="BusinessName" id="name" placeholder="Name of Upload" readonly>
            </div>
   
            <div class="form-group">
                <label>Month and Year of Incorporation</label>
                <input type="date" class="form-control" name="MonthandYearofIncorporation" required>
            </div>
            ... A very long form
            <input class="btn btn-md btn-success" type="submit" value="Apply for Carbon"/>
        </form>
       ...
    </body>
    <script>
      //...
      function submitter(data_process){
        // Run server-side function when submitted.
        google.script.run
            .withSuccessHandler(function(){
              //alert('Thank You!!! Your application has been received');
              window.top.location.replace("https://stackoverflow.com");
            })
            .withFailureHandler(function(e){
              alert("Unable to submit your application. Please contact us.");
              })
            .SendHtmlMail(data_process); // Server-side form processing    
      }
    </script>
</html>

ScriptApp.getService().getUrl()
returns you an Url of type
https://script.google.com/macros/s/XXX/dev
instead of
https://script.google.com/macros/s/XXX/exec,
so the developper version instead of the published version.
The former is subjected to some restrictions:
This URL can only be accessed by users who have edit access to the
script. This instance of the app always runs the most recently saved
code — not necessarily a formal version — and is intended for quick
testing during development.
See also here.
If you change dev to exec this should solve your issue.
UPDATE:
Either ScriptApp.getService().getUrl() gives you the dev or exec URL depends on how you deploy the WebApp.
When you deploy as a new version you have the option to
"Test web app for your latest code":
this will give you the dev version.
If you instead run the WebApp by copy-pasting the
Current web app URL into your browser:
your doGet() function will automatically retrieve the correct exec URL with ScriptApp.getService().getUrl().

Related

printing a textarea from a form

I'm in the process of printing an HTML form. After checking via the internet, I am unable to print all the input. Here's what I have now:
`
<script type="text/javascript">
  function CopyElem(elem)
  {
      $('form input[type=text]').each(function() {
        $(this).attr('value', $(this).val());
      });
 
      $('form input[type=date]').each(function() {
        $(this).attr('value', $(this).val());
      });
 
      $('form input[type=checkbox]').each(function() {
        $(this).attr('checked', $(this).prop("checked"));
      });
 
  }
  function PrintElem(elem)
  {
      Popup($(elem).html());
  }
 
  function Popup(data)
  {
      var mywindow = window.open('', 'myfrm');
      mywindow.document.write('<html><head><title>Behandelformulier</title>');
      mywindow.document.write('</head><body >');
      mywindow.document.write(data);
      mywindow.document.write('</body></html>');
 
      mywindow.document.close(); // necessary for IE >= 10
      mywindow.focus(); // necessary for IE >= 10
 
      mywindow.print();
      mywindow.close();
 
      return true;
  }
`
only it does not print the content of the "input type="textarea". You won't see it in print preview either. What am I doing wrong?
I've been searching the internet for days, but can't find anything about it.
I've found the solution for my problem.
In the function CopyElem(elem) I placed
function CopyElem(elem) {
$('form textarea').each(function () {
$(this).text($(this).val());
});
}

How to redirect page when select option HTML, Laravel

I need to redirect page when one of the option is selected.
<select required name="subject" id="konu" class="form-control">
<option value="" disabled>Choose Subject</option>
<option value="Ask a question">Ask a question</option>
<option value="Leave a comment">Leave a comment</option>
<option value="Where to buy">Where to buy</option>
<option value="Product Complaint">Product Complaint</option>
<option value="Other">Other</option>
<option {{ request('subject') == 'Request SDS' ? 'selected' : '' }} value="Request SDS">Request SDS</option>
<option value="Distributor">Request Distributorship</option>
</select>
I once needed this too and found that your question has already been answered.
If you're fine with using inline JavaScript, check out this answer:
https://stackoverflow.com/a/7562129/10440010
If you prefer staying off of inline, check out this answer under the same question:
https://stackoverflow.com/a/7562201/10440010
I hope this helps!
Update:
An easy way of making it work for specific options, is to make the onChange event check whether the value of the clicked option equal to something. In the snippet below, I make it work for all links starting with HTTPS.
HTML:
<select id="redirectSelect">
<option value="NoLink" disabled>Please select</option>
<option value="NoLinkEither">Option 1</option>
<option value="https://www.google.com/">External Link</option>
</select>
JavaScript:
function redirect(goto) {
var conf = confirm("Are you sure you want to go elswhere?");
if (conf && goto != '') {
window.location = goto;
}
}
var selectEl = document.getElementById('redirectSelect');
selectEl.onchange = function() {
if (this.value.startsWith('https')) {
var goto = this.value;
redirect(goto);
}
};
Hopefully this helps you enough to solve your problem. If not, leave a comment and I am glad to help!
I have a code previously woked.Here is select
<select required name="subject" id="konu" class="form-control">
                                <option value="" disabled>Choose Subject</option>
                                <option value="Ask a question">Ask a question</option>
                                <option value="Leave a comment">Leave a comment</option>
                                <option value="Where to buy">Where to buy</option>
                                <option value="Product Complaint">Product Complaint</option>
                                <option value="Other">Other</option>
                                <option {{ request('subject') == 'Request SDS' ? 'selected' : '' }}  value="Request SDS">Request SDS</option>
                                <option value="Distributor">Request Distributorship</option>
                            </select>
Here it is script.
$( document ).ready(function() {
        $("#konu").change(function(){
                var value = $("#konu").val();
                if(value=="distributor"){
                    window.location = 'be-our-distributor';
                }
            })
        });
For the second answer, the value used in your HTML differs from the value you're checking against in the JavaScript code.
In your HTML, it's Distributor and in your JavaScript code it's distributor. Mind the capital D.
the problem is on your condition. Your value is Distributor and u using distributor. Js is case sensetive so you not getting any redirection. the code should look like
$( document ).ready(function() {
$("#konu").change(function(){
var value = $("#konu").val();
if(value=="Distributor"){
window.location = 'be-our-distributor';
}
})
});

How to get the html form value from razor page?

I have a form having Name and isVisible as checkbox. data is loaded from api. now i want to edit the visibility status of the names (section names). i have checkbox for the visibility which is okay but what about names how to get the id of the name against the checkbox selected.
html code:
<div class="col-md-12 bg-white p-5 rounded-8">
<div class="col-md-12 text-right mt-3">
<button type="submit" id="btnSaveSectionVisibility" value="Save" class="btn btn-custom">Save</button>
<a class="btn btn-custom" id="lnksectionVisibileCancel">Cancel</a>
</div>
<form class="row row-margin-zero needs-validation" asp-controller="Group" asp-action="AddVisibility" method="Post" id="frmAddSectionVisibility" autocomplete="off" novalidate>
<table class="research" border="1" style="background-color:azure;text-transform:full-width">
<tbody>
#foreach (var groups in Model)
{
<tr class="accordion" style="cursor:pointer">
<td colspan=#Model.Count.ToString() ;>#groups.Name</td>
</tr>
}
<tr>
<td><strong>Section</strong></td>
<td><strong>Visibility</strong></td>
</tr>
#foreach (var groups in Model)
{
for (int i = 0; i < groups.SectionRespnses.Count; i++)
{
<tr>
<td>#groups.SectionRespnses[i].Name</td>
<td><input type="text" class="chk" name="name4" id="groups.SectionRespnses[i].id"/>#groups.SectionRespnses[i].Name</td>
<td><input type="checkbox" class="chk" name="name4" /></td>
</tr>
}
}
</tbody>
</table>
</form>
</div>
javascript:
<script>
$(function () {
$(".research tr:not(.accordion)").hide();
$(".research tr:first-child").show();
$(".research tr.accordion").click(function () {
$(this).nextAll("tr").fadeToggle(500);
}).eq(0).trigger('click');
});
$("#btnSaveSectionVisibility").click(function () {
var form = $("#frmAddSectionVisibility");
alert(form);
//if (form.valid()) {
var url = form.attr("action");
var lists = [];
$('.chk:checked').each(function () {
var data = [
$(this).val()
]
lists.push(data);
});
// var data = form.serialize()
var sectionCreateRequest = {
GroupId: $("#hdnGroupId").val(),
SectionIds: lists
}
$.ajax({
type: 'Post',
url: url,
data: sectionCreateRequest
}).done(function (response) {
if (response.toLowerCase().indexOf("success") >= 0) {
toastr.success(response);
/* GetAllGroups();*/
//LoadRolesTable()
}
else
toastr.info(response);
});
});
</script>
how to get the id of the name against the checkbox selected
Do you mean you want to get the textbox’s id attribute when you checked the checkbox?
To get the textbox’s id attribute, we could use the checkbox click event, after checking the checkbox, we could find its parent element (the <tr> element), then we can find the textbox based on its type (since there only have one textbox in the selected row), and get the id attribute.
1.Add two <div> at the end of the form. They are used to display the selected id value.
<tr>
<td>#groups.SectionRespnses[i].Name</td>
<td><input type="text" class="chk" name="name4" id="#groups.SectionRespnses[i].id"/>#groups.SectionRespnses[i].Name</td>
<td><input type="checkbox" class="chk" name="name4" /></td>
</tr>
<div id="selectedLabel" style="display:none"></div>
<span id="selected"></span>
[Note]: When you bind the id attribute, the code should be id="#groups.SectionRespnses[i].id"
2.js Demo as below.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function () {
//get all
var $all = $('.chk');
//get the area to write the results
var $selectedListing = $('#selected');
//get the label
var $selectedLabel = $('#selectedLabel');
//when you click a checkbox, do the logic
$all.on('click', function () {
//set the content of the results
$selectedListing.html(
//only return those that are checked
$all.filter(':checked').map(function (index, checkbox) {
//return a id of the name against the checkbox selected
var id = $(this).parent().parent().find("input[type='text']").attr("id");
return id;
}).get() //get a id of the name against the checkbox selected
);
//hide the label if no checkboxes are selected
if ($selectedListing.text().trim().length) {
$selectedLabel.show();
} else {
$selectedLabel.hide();
}
});
});
</script>
Result:
For Example Creating a Simple HTML Form:
In Form.cshtml
<!DOCTYPE html>
<html>
    <head>
        <title>Customer Form</title>
    </head>
    <body>
      <form method="post" >
        <fieldset>
          <legend>Add Customer</legend>
          <div>
            <label for="CompanyName">Company Name:</label>
            <input type="text" name="CompanyName" value="" />
          </div>
          <div>
            <label for="ContactName">Contact Name:</label>
            <input type="text" name="ContactName" value="" />
          </div>
          <div>
            <label for="Employees">Employee Count:</label>
            <input type="text" name="Employees" value="" />
          </div>
          <div>
            <label> </label>
            <input type="submit" value="Submit" class="submit" />
          </div>
        </fieldset>
      </form>
    </body>
</html>
Reading User Input from the Form:
To process the form, you add code that reads the submitted field values and does something with them. This procedure shows you how to read the fields and display the user input on the page.
At the top of the Form.cshtml file, enter the following code:
#{
    if (IsPost) {
        string companyname = Request.Form["companyname"];
        string contactname = Request.Form["contactname"];
        int employeecount = Request.Form["employees"].AsInt();
        <text>
          You entered: <br />
          Company Name: #companyname <br />
          Contact Name: #contactname <br />
          Employee Count: #employeecount <br />
        </text>
    }
}

Can't find Pi Point after create

I have C# application that creates a new Pi Point using the code based on 
PI-AF-SDK-Basic-Samples/CreatePIPointsExample.cs at master · osisoft/PI-AF-SDK-Basic-Samples · GitHub 
The point seems to be created ok - here's a screen grab following a tag search in SMT:
My problem is, when my same C# application searches for the newly created Pi Point is doesn't find it.
The code for the search is as follows:
       
private static List<PIPoint> GetPiPoints(PIServer piServer)
        {
            var criteria = GetCriteria("61");
            var foundPoints = PIPoint.FindPIPoints(piServer, criteria).ToList();
            criteria = GetCriteria("63");
            foundPoints.AddRange(PIPoint.FindPIPoints(piServer, criteria).ToList());
            criteria = GetCriteria("64");
            foundPoints.AddRange(PIPoint.FindPIPoints(piServer, criteria).ToList());
            return foundPoints;
        }
private static List<PIPointQuery> GetCriteria(string location)
        {
            List<PIPointQuery> criteria = new List<PIPointQuery>();
            PIPointQuery whereClause1 = new PIPointQuery(PICommonPointAttributes.Location1, OSIsoft.AF.Search.AFSearchOperator.Equal, location);
            PIPointQuery whereClause2 = new PIPointQuery(PICommonPointAttributes.PointSource, OSIsoft.AF.Search.AFSearchOperator.Equal, "o");
            criteria.Add(whereClause1);
            criteria.Add(whereClause2);
            return criteria;
        }
So, my understanding is that this should find all points that have a "location1" attribute value of 61, 63 or 61 AND a "pointSource" of "o" - I have tried uppercase and lower case "o"
From the screenshot, you can see that this is the case for the newly created "Kuba_99x" tag yet it is not found in the search, although thousands of other existing tags are.
Any ideas where I went wrong please?
The Pi code was actually fine. Problem was, my code was filtering the newly created record after the selection.
Location1 is stored as an Int32 on the PI Data Archive. The location parameter needs to be an int instead of string.
Further questions will be addressed at OSIsoft PI Square since you also have a post there.

Google chart x axis with decimal places

I'm attempting to create a basic google chart.
X axis is a time, y axis is a value.
Data is formatted as so:
<html>
<head>
  <script type="text/javascript" src="https://www.google.com/jsapi"></script>
  <script type="text/javascript">
    google.load('visualization', '1.1', {packages: ['line']});
    google.setOnLoadCallback(drawChart);
    function drawChart() {
      var data = new google.visualization.DataTable();
      data.addColumn('number', 'Time');
      data.addColumn('number', 'Yesterday');
      data.addColumn('number', 'Today');
      data.addColumn('number', 'TwoDayAgo');
      data.addRows([
        [01.00,  37.8, 80.8, 41.8],
        [02.00,  30.9, 69.5, 32.4],
        [03.00,  25.4,   57, 25.7],
        [04.00,  11.7, 18.8, 10.5],
        [05.00,  11.9, 17.6, 10.4]
      ]);
      var options = {
        chart: {
          title: 'Results',
          subtitle: 'Comparison'
        },
        width: 900,
        height: 500
      };
      var chart = new google.charts.Line(document.getElementById('linechart_material'));
      chart.draw(data, options);
    }
  </script>
</head>
<body>
  <div id="linechart_material"></div>
</body>
</html>
Note the decimal places in the data table.
If I remove the decimal places it will work om
However the chart does not show?