How to only send HTTP response as plain text (HTML) [duplicate] - html

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 2 years ago.
I need to implement a calculator on my webpage, which will receive some arguments in the url and is supposed to return just the result, nothing else.
Example:
http://example.com/calc/?x=244&y=123&op=plus
I wrote a program using HTML and JavaScript which returns the correct result and prints it on the webpage.
This prints the result.
But the client doesn't just receive the result, but the whole html & script. Does anyone know how I can send only the result to the client?
Edit: If this cannot be done with HTMP and JS, how else?
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function calculate(url) {
// ...
}
let url = window.location.href;
document.write(parseInt(calculate(url)));
</script>
</body>
</html>
Desired result: 367 is returned to the HTTP client
Actual result: < !DOCTYPE html> .... ...... is returned to the HTTP client

Try the following
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
function calculate (url_string) {
try {
var url = new URL(url_string);
var x = parseInt(url.searchParams.get("x"));
var y = parseInt(url.searchParams.get("y"));
switch(url.searchParams.get("op")){
case "plus": return x + y;
// add more cases here
}
} catch(e){}
}
let url = window.location.href;
document.write(parseInt(calculate(url)));
</script>
</body>
</html>

Related

Google Apps Script - Passing Variable from a Script to an HTML then back to a Script and one last time to an HTML

I am having troubles passing 1 variable (dateToExport) into an HTML "showConflict_HTML" and then running a function/script within that HTML by passing dateToExport.
1 Script ("exportButton")
1 HTML ("showConflict_HTML")
The Process goes like this:
The script "exportButton" runs passing (dateToExport) into it
And then the "showConflict_HTML" html pops up in which the user clicks a button "Yes, Overwrite and Export"
The script "exportButton" then runs again and passes the dateToExport into it again
When I click the "Yes, Overwrite and Export", nothing happens and the "google.script.run.exportOrderData(1, dateToExport_captured);" does not run in the HTML. Also there is no error given so I can not figure out why. Anyone have any idea why?
function exportOrderData(override, dateToExport) {
if(override == 1){
execute_exportOrderData();
easterEgg = 1;
}
else if(override == 0){
var userInterface = HtmlService
.createHtmlOutputFromFile('showConflict_HTML');
userInterface.dateToExportFromServerTemplate = dateToExport;
SpreadsheetApp.getUi()
.showModelessDialog(userInterface, 'Existing Customer Order(s) on ' + dateWithConflict);
}
}
<!-- "showConflict_HTML". This HTML file is will run the exportOrderData function once the Override button ("my_button") has been clicked !-->
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<link href="https://fonts.googleapis.com/css2?family=Comic+Neue&display=swap" rel="stylesheet">
</head>
<body>
<button id='my_button'>Yes, Overwrite and Export</button>
<script>
`THIS SHOULD PASS THE dateToExport Varaible so we can access it in this HTML Script`
var dateToExport_captured = dateToExportFromServerTemplate;
// Once the Button is Clicked, the following occurs
document.getElementById('my_button').addEventListener('click', _ => {
// Once the Button is Clicked, the Loading Circle Effect Function will start running here
google.script.run.loadingCircleEffect();
google.script.run.exportOrderData(1, dateToExport_captured);
});
</script>
</body>
</html>
function exportOrderData(override, dateToExport) {
Try using force-printing scriptlets in your HTML, along the lines of this:
var dateToExport_captured = <?!= JSON.stringify(dateToExportFromServerTemplate) ?>;
Notes:
JSON.stringify can be omitted if your value is a string or a number.
Per the documentation, you should NOT use this technique if dateToExport comes from untrusted users. If it's your own system that generates it then you should be fine.
Although this is not an answer it may shed some light on what is wrong with your code.
To pass dateToExportFromServerTemplate to the html page you need to change the code in exportOrderData as below using templated html createTemplateFromFile
var userInterface = HtmlService.createTemplateFromFile('showConflict_HTML');
userInterface.dateToExportFromServerTemplate = dateToExport;
userInterface = userInterface.evaluate();
For the page to receive the variable you need to use a scriptlet.
var dateToExport_captured = <?= dateToExportFromServerTemplate ?>
But what I don't understand is dateToExportFromServerTemplate never changes so why display a new page?
So I was able to fix this by using localStorage.setItem('dateToExport_transfer',dt) in the HTML where the user selects the date and then in my "showConflict_HTML" HTML I call var dateToExport_captured = localStorage.getItem('dateToExport_transfer') to grab that date from the other HTML.

Parsing Html Page with Dart

I m trying to parse the following entry in an HTTP get request.
In the body, you see a script tag with a function call where I need to have access to the JSON inside the HTML tag.
<!DOCTYPE html>
<html translate="no">
<head></head>
<body>
<script>
$(function() {
intranet.list.frontend.init({
gridDataAndConfiguration: {
"Here is a big Json - WANTED"
},
},
});
</script>
</body>
</html>
Up to now, I don't parse the HTML with any Dart specific parsing method like
"parse" from package:html/parser.dart. That attempt was successful in searching for all the "script" tags inside the HTML DOM, but unfortunately, I did not find or showed the JSON or function call inside the referred script Tag!
The question is, how to access the JSON in the given HTML Page using Dart?
Solution :
RegExp re = RegExp(r'\[\{.*?\}\]');
var parsedHtml = parse(htmlText);
var allScripts = parsedHtml.getElementsByTagName('script');
for (int i = 0; i < allScripts.length; i++) {
if (allScripts[i].innerHtml.contains(startString)) {
Iterable<String> result =
re.allMatches(allScripts[i].innerHtml).map((m) => m[0]);
List<dynamic> jsonParsed = [];
for (var match in result) jsonParsed.add(jsonDecode(match));
Thanks for your answer & help.

Parse multi level JSON from URL

All.
I found this script which is rather promising for what I am trying to do.
It works great with the hardcoded XML script.
However, I need to parse the file itself from an external URL.
Thank You.
Contents of the example file.
{"icestats":{"admin":"admin","host":"192.168.2.203","location":"Radio","server_id":"Icecast 2.4.4","server_start":"Mon, 24 May 2021 16:54:10 +0000","server_start_iso8601":"2021-05-24T16:54:10+0000","source":{"audio_info":"channels=2;samplerate=44100;bitrate=256","channels":2,"genre":"various","listener_peak":3,"listeners":2,"listenurl":"http://192.168.2.203:8000/RadioOne","samplerate":44100,"server_description":"Unspecified description","server_name":"RadioOne","server_type":"audio/mpeg","stream_start":"Mon, 24 May 2021 21:59:34 +0000","stream_start_iso8601":"2021-05-24T21:59:34+0000","title":"KISS - Hide Your Heart","dummy":null}}}
Example of the linked file. (This is an example of the URL file, in the real-world URL, it will be my domain name, with the file attached to it. This file cannot be removed from the location it is at, it is sitting on another server in the network.)
http://192.168.2.203:8000/status-json.xsl
Full script (This will run and show the hardcoded XML tree without any modifications to the file)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Parse Nested JSON Data in JavaScript</title>
</head>
<body>
<script>
/* Storing multi-line JSON string in a JS variable
using the new ES6 template literals */
var json = '{"icestats":{"admin":"admin","host":"192.168.2.203","location":"Radio","server_id":"Icecast 2.4.4","server_start":"Mon, 24 May 2021 16:54:10 +0000","server_start_iso8601":"2021-05-24T16:54:10+0000","source":{"audio_info":"channels=2;samplerate=44100;bitrate=256","channels":2,"genre":"various","listener_peak":3,"listeners":2,"listenurl":"http://192.168.2.203:8000/RadioOne","samplerate":44100,"server_description":"Unspecified description","server_name":"RadioOne","server_type":"audio/mpeg","stream_start":"Mon, 24 May 2021 21:59:34 +0000","stream_start_iso8601":"2021-05-24T21:59:34+0000","title":"KISS - Hide Your Heart","dummy":null}}}';
// This is the link to the file; the file contents are what is above.
//var json = "http://192.168.2.203:8000/status-json.xsl";
// Converting JSON object to JS object
var obj = JSON.parse(json);
// Define recursive function to print nested values
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
document.write(obj[k] + "<br>");
};
}
};
printValues(obj);
document.write("<hr>");
document.write(obj["icestats"]["source"]["title"]);
</script>
</body>
</html>
When I run the script with the URL link only, I get the following error.
Uncaught SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
at music2.asp:18
Which points to this line.
var obj = JSON.parse(json);
This code was provided for me and it works great.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Zvonko *</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
<script>
// fetch the JSON data from your URL:
jQuery.get( "http://localhost:8000/status-json.xsl" , showData, "json" );
function showData(data){
// no need to Converting JSON string to JS object
// jQuery converted it for you
//var obj = JSON.parse(data);
printValues(data);
document.write("_______________________________");
if(data["icestats"] && data["icestats"]["source"]){
document.write(data["icestats"]["source"]["title"]);
// This next line, I use to pass a variable to an input field to submit to the database.
$(".myid").val(data["icestats"]["source"]["title"]);
}
// Converting your JSON string from top to JS object
var jsonobj = JSON.parse(yourJson);
printValues(jsonobj);
document.write("_______________________________");
if(jsonobj["icestats"] && data["icestats"]["source"]){
document.write(jsonobj["icestats"]["source"]["title"]);
}
}
// Define recursive function to print nested values
function printValues(obj) {
for(var k in obj) {
if(obj[k] instanceof Object) {
printValues(obj[k]);
} else {
document.write(k + ": " + obj[k]);
};
}
};
</script>
</body>
</html>
<form action="Send.asp" method="post">
<input type="text" name="Title" class="myid" style="border:1px double #000;">
<input type="submit" name="Submit">
</form>
Thanks to, Zvonko, for the code, on another side.
This one is completed.

How do I change query in my google JSON Search API?

I have used the example below successfully for my own cse search engine by changing cx and API-key. I am now creating a form for my users to be able to change the query. I therefore want to change the &q=cars in the example to a string that changes according to form input. My string name is que and I have tried &q=" + que + " and about a thousand other ways without success. I either get a search result list for the word que or no results at all? Any ideas? How is the proper syntax supposed to be?
<html>
<head>
<title>JSON Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<script>
function hndlr(response) {
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
// in production code, item.htmlTitle should have the HTML entities escaped.
document.getElementById("content").innerHTML += "<br>" + item.htmlTitle;
}
}
</script>
<script src="https://www.googleapis.com/customsearch/v1?key=YOUR-KEY&cx=017576662512468239146:omuauf_lfve&q=cars&callback=hndlr">
</script>
</body>
</html>
It isn't a good idea to use the JSON API in client-side code running in a browser, since your API key will be viewable by anybody.
You should use the Custom Search Element for this case: https://developers.google.com/custom-search/docs/tutorial/implementingsearchbox

Mustache.js iterate over all arrays

I'm still busy trying to setup a JSON file to a HTML website. So if the json changes the changes are dynamically loaded in the HTML. Till this far i'm able to retreive the content and even request some content. But not everything that i want because the markup from the JSON is a bit weird.
Because of the cross-site protection I was not able to do a JSOP request directly, so i solved that with a little trick i saw somewhere. I've created a test.php that simply does:
That way I circumvent the cross-site protection, and everything works well. Only problem is that I can't iterate over all the arrays that i want. Currently i'm using the following script to do a JSOP call and get the data. And the output is a nice description between the <li></li>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
</head>
<body>
<ul id="episodes">
</ul>
<script src="http://cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js"></script>
<script src="http://ps3scenefiles.com/json/handlebars.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script id="episodes-template" type="text/template">
<li>{{description}}</li>
</script>
<script>
$(function() {
$.getJSON('http://ps3scenefiles.com/json/test.php', function(data) {
var template = $('#episodes-template').html();
var info = Mustache.to_html(template, data);
$('#episodes').html(info);
});
});
</script>
</body>
</html>
But when you open the link to the JSON (http://ps3scenefiles.com/json/test.php), you see that the Episodes array has another array with just numbers. How can i create a list like
Episode: 1
Id:13605 Active:true Lang:en Link: url
Id:16525 Active:true Lang:ru Link: url
Episode: 2
Id:14854 Active:true Lang:en Link: url
Id:19445 Active:true Lang:ru Link: url
So to be clear, how can i do a mustache (or handlebars) templating to make it look like the example?
You can use Handlebars helper as mentioned in this answer
Here is a fiddle without styling, that prints out the data you expect (sort of, not all fields).
Here is the helper function -
Handlebars.registerHelper('eachkeys', function(context, options) {
var fn = options.fn, inverse = options.inverse;
var ret = "";
var empty = true;
for (key in context) { empty = false; break; }
if (!empty) {
for (key in context) {
ret = ret + fn({ 'key': key, 'value': context[key]});
}
} else {
ret = inverse(this);
}
return ret;
});