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

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

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.

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

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>

jQuery function preventing nested <body> elements from being read

My assignment is to create a Twitter clone with HTML, CSS, and jQuery. I have been provided a jQuery function that generates 10 tweets, but when I call it in <scripts>, I am only able to get it to run in the <body> tag, and all of my changes to HTML and CSS are canceled out. Basically it just spits out 10 tweets on top of my singular background.
<script>
$(document).ready(function(){
var $body = $('body');
$body.html('Twitter-Clone');
var $tweets = $("tweets-container");
var index = streams.home.length - 1;
while(index >= 0){
var tweet = streams.home[index];
var $tweet = $('<div></div>');
$tweet.text('#' + tweet.user + ': ' + tweet.message);
$tweet.appendTo($body);
index -= 1;
}
});
</script>
And if I write something like
$tweet.appendTo($tweets) <!--or-->
$tweet.appentTo("#tweets-container");
Tweets do not show up at all, AND my page ignores all the HTML and CSS I've written aside from what's at the top of <body>
I really want to know, how can I apply this function to my <div>"tweets-container", and why does the code seem to skip over all of my elements nested in <body> after execution?
I think once I figure this out, it'll be a huge step in the right direction. Any help is very much appreciated! Can supply additional code if needed.

Chrome extension used to refresh pages

I was trying to develop a Chrome extension that can display me the last 3 news from a soccer news site (obviously the page is not open in any tab), by refreshing every 5 minutes. My ideea was to load the page inside an iframe and, once the page is loaded, access the page DOM and extract only the text nodes with the news. I've tried in many ways using ready and load functions, I tried to follow this solutions here but i always get warnings. My question is: is there a way I can do that without having troubles with cross-domain security? Are there any simple examples i can use?
Here's how you could do it using JQuery (please keep in mind I dont know JQuery, just saw this approach somewhere and thought it might work for you).
I put this in a popup and it worked....
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script>
function renderNews(newsList){
$('#news').html('');
$(newsList).each(function(i,item){
var link = document.createElement('a');
$(link).attr('href',item.link);
$(link).html(item.description);
$(link).click(function(){
chrome.tabs.create({url:$(this).attr('href')});
});
var linksDate = document.createElement('span');
//$(linksDate).text(item.date);
$(linksDate).text(item.day + '-' + item.month + ' ' + item.hour + ':' + item.minute+' - ');
var listItem = document.createElement('li');
$(listItem).append(linksDate).append(link);
$("#news").append(listItem);
});
}
function getNews() {
$.get("http://www.milannews.it/?action=search&section=32", null, function(data, textStatus)
{
if(data) {
var news=$(data).find(".list").find('li').slice(0,3) ;
$("#status").text('');
var newsList=[];
$(news).each(function(i, item){
var newsItem={};
newsItem.description=$(item).find('a').html();
newsItem.link='http://www.milannews.it/'+$(item).find('a').attr('href');
newsItem.date=$(item).find('span').first().text();
newsItem.day=newsItem.date.split(' ')[0].split('.')[0];
newsItem.month=newsItem.date.split(' ')[0].split('.')[1];
newsItem.hour=newsItem.date.split(' ')[1].split(':')[0];
newsItem.minute=newsItem.date.split(' ')[1].split(':')[1];
newsList[i]=newsItem;
});
renderNews(newsList);
localStorage.setItem('oldNews',JSON.stringify(newsList));
}
});
}
function onPageLoad(){
if (localStorage["oldNews"]!=null) renderNews(JSON.parse(localStorage["oldNews"]));
getNews();
}
</script>
</head>
<body onload="onPageLoad();" style="width: 700px">
<ul id="news"></ul>
<div id="status">Checking for new news...</div>
</body>
</html>
And dont forget to put the urls your getting with the xhr stuff in the permissions part of your manifest....
http://code.google.com/chrome/extensions/xhr.html
Use xhr to load the page and use jQuery or a regex to parse the raw HTML for the data you are looking for.
Keep in mind that the destination site may not want to you access their site in such an automated fashion. Be respectful of their site and resources.

Access Individual Google Maps Elements (Distance, Time, Directions)

How do you access individual elements in Google Maps?
Is there a way to do this through the API or will I have to parse the DOM and pull the elements (e.g., distance, time, directions) separately? Version 2 or 3 of the API is fine.
Example:
<div jstcache="6" style="text-align: right; padding-bottom: 0.3em;"
jseval="this.innerHTML = $Route.summaryHtml">38.9 mi (about 40 mins)</div>
I want just the distance (e.g., 38.9 mi) for a Javascript calculation. If nothing exists in the API, I'll parse it out manually.
Thanks,
Mark
Note: This is the full example site I'm using: http://code.google.com/intl/en-EN/apis/maps/documentation/examples/directions-advanced.html
Update with simplified solution:
For those that need it, here is a very simple full HTML page that I was able to thin out from the example that Cannonade posted. This has all styling and other scripts removed:
<html>
<head>
<script src="maps.google.com/maps?file=api&v=2.x&a…; type="text/javascript"></script>
<script>
function initialize()
{
alert("loading ...");
if (GBrowserIsCompatible())
{
var wp = new Array ();
wp[0] = new GLatLng(32.742149,119.337218);
wp[1] = new GLatLng(32.735347,119.328485);
directions = new GDirections(); directions.loadFromWaypoints(wp);
GEvent.addListener(directions, "load", function()
{
alert(directions.getDuration().seconds);
});
}
else
{
alert("Sorry, the Google Maps API is not compatible with this browser");
}
}
</script>
</head>
<body onload="initialize();" onunload="GUnload();"></body>
</html>
Put the codesamples into index.html and you'll be set.
You you can get the individual properties of a GDirections::loadFromWaypoints request in the response.
getDuration - The duration in seconds for the travel time.
getDistance - The distance in meters or a localized string describing the distance.
You can find an example of getting the travel time here (src).