google Custom Search api in a js file - javascript

First I found the demo in google doc:
<html>
<head>
<title>JSON/Atom Custom Search API Example</title>
</head>
<body>
<div id="content"></div>
<script>
function hndlr(response) {
// handle result
}
</script>
<script src="https://www.googleapis.com/customsearch/v1?key=KEY&cx=cx&q=cars&callback=hndlr">
</script>
</body>
</html>
And it works fine.
But know I want to trigger the "search process" inside a js file say mySearch.js, so how can I get this done ?
example:
var XXXLayer = cc.Layer.extend({
init:function () {
this._super();
var theUrl = 'https://www.googleapis.com/customsearch/v1?key=KEY&cx=cx&q=cars&callback=hndlr';
// what to do here ???????
return true;
},
hndlr:function(response) {
// handle result
}
});
Any suggestion would be appreciated thanks :)

You could add a script element, when you trigger the search process.
function triggersearch(){
var query=document.getElementById("query").value;
var JSElement = document.createElement('script');
JSElement.src = 'https://www.googleapis.com/customsearch/v1?key=KEY&cx=KEY&q='+query+'&callback=hndlr';
document.getElementsByTagName('head')[0].appendChild(JSElement);
}

using the code from #RamK, do the following:
index.html:
<html>
<head>
<title>Example</title>
</head>
<body>
<div id="query"></div>
<script src="cs.js"></script>
</body>
</html>
cs.js:
var key = "your api key"; // API KEY
var id = "your custom search engine id"; // CSE ID
var q = "cats"; // QUERY
function hndlr(response) {
console.log(response); // a way to see your results
}
function triggersearch(){
var query=document.getElementById("query").value;
var JSElement = document.createElement('script');
JSElement.src = `https://www.googleapis.com/customsearch/v1?key=${key}&cx=${id}&q=${q}`+query+'&callback=hndlr';
document.getElementsByTagName('head')[0].appendChild(JSElement);
}
triggersearch();

Related

How to get data from jquery form builder if there are multiple form initialized on the same page

I have a code like this:
<html>
<head>
<title>Example formBuilder</title>
</head>
<body>
<div class="build-wrap"></div>
<div class="build-wrap"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<script>
jQuery(function($) {
$(document.getElementsByClassName('build-wrap')).formBuilder();
});
</script>
</body>
</html>
If it was initialized by id, then I could have get data with something like this:
var fbEditor = document.getElementById('build-wrap');
var formBuilder = $(fbEditor).formBuilder();
document.getElementById('getJSON').addEventListener('click', function() {
alert(formBuilder.actions.getData('json'));
});
However, I am using classname to initialize form builder. Is there any way, when click on save, get the respective form-builder data? I am using https://formbuilder.online/
Here is jsfiddle: https://jsfiddle.net/xycvbj3r/3/
#PS: there could be numerous form builder inside php loop.
You can try this:
formBuilder.actions.getData('json');
Or:
formBuilder.actions.getData();
The live demo is here: http://jsfiddle.net/dreambold/q0tfp4yd/10/
I was facing the same issue too. This worked for me
var list = ['#ins1', '#ins2', '#ins3'];
var instances = [];
var init = function(i) {
if (i < list.length) {
var options = JSON.parse(JSON.stringify([]));
$(list[i]).formBuilder(options).promise.then(function(res){
console.log(res, i);
instances.push(res);
i++;
init(i);
});
} else {
return;
}
};
init(0);
And to get data, you can use instances[key].actions.getData()
I am not sure how you are planning to save this data, but to help with your problem of getting form data for a particular form you can use something like this
var formBuilder = $(document.getElementsByClassName('build-wrap')).first().data('formBuilder').actions.getData()
Or to use it over a jQuery Collection then
$(document.getElementsByClassName('build-wrap')).each(function () {
var formBuilder = $(this).data('formBuilder').actions.getData()
})
There is a callback mentioned in the documentation, onsave which runs on editor save. So, when clicking on any form builder's save button, the respected form's data can be received.
Here is the code-
<html>
<head>
<title>Example formBuilder</title>
</head>
<body>
<div class="build-wrap"></div>
<div class="build-wrap"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<script src="https://formbuilder.online/assets/js/form-builder.min.js"></script>
<script>
jQuery(function($) {
var options = {
onSave: function(evt, formData) {
// This is the respected form's data
console.log('MY DATA_________', formData)
},
};
$(document.getElementsByClassName('build-wrap')).formBuilder(options);
});
</script>
</body>
</html>
Here is the fiddle (couldn't create a working snippet due to not working CDNs.
)- https://jsfiddle.net/nehasoni988/rpo1jnuk/1/#&togetherjs=Mka9TJ4cex

Function parameter is not being passed. How to correctly pass parameter into function of another JavaScript file?

I want to to call a function file2Function(getValue) of a file (page2.js) from another JavaScript File (page1.js) to open new page in browser and display some data on it using parameter passed viamyFunction1(e) into file2Function as file2Function(itemFromItems). So file2Function(getValue)should take value of var itemFromItems and should display on page2.html. But it is displaying "undefined" for getValue. Kindly help me finding out where I am doing Mistake. Thank You.
// page1.js
function file1Function()
{
var secPage1 = document.getElementById("page1Section");
var heading = document.createElement("h4");
var anchor= document.createElement('a');
anchor.setAttribute('href',"#");
anchor.innerText = "Click Me";
anchor.addEventListener("click", myFunction1);
heading.appendChild(anchor);
secPage1.appendChild(heading);
anchor.id=1;
function myFunction1(e) {
var itemFromItems = e.currentTarget.getAttribute("id");
console.log("item",itemFromItems);
file2Function(itemFromItems);
}
}
// page2.js
var globalVar;
function file2Function(getValue)
{
console.log("getValue",getValue);
window.open("page2.html");
// window.open("https://www.google.com/");
globalVar=getValue;
console.log("globalVarNow",globalVar);
}
function loadDynamicData()
{
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}
<!-- page1.html -->
<!DOCTYPE html>
<html>
<head>
<script src="js/page1.js"></script>
<script src="js/page2.js"></script>
</head>
<body onload="file1Function()">
<h3>This is page1</h3>
<section id="page1Section">
</section>
<script>
</script>
</body>
</html>
<!-- page2.html -->
<!DOCTYPE html>
<html>
<head>
</head>
<body onload="loadDynamicData()">
<h3>This is page2</h3>
<section id="page2Section">
</section>
<p id="paraId"></p>
<script src="js/page2.js"></script>
</body>
</html>
The problem is that globalVar is a global variable, but the value you are assigning to it in file2Function() is accessable only within its scope, that is why you are getting undefined, because loadDynamicData() has no access to the new value of globalVar.
You could call loadDynamicData() from file2Function() and pass getValue as an argument, but since you need to open page2 before executing loadDynamicData() it won't work.
What I suggest is you pass getValue along with your URL as a query parameter and get it from inside loadDynamicData(), it'll work fine.
SOLUTION:
function file2Function(getValue)
{
window.open("page2.html?value="+getValue);
// window.open("https://www.google.com/");
}
function loadDynamicData()
{
var url_string = window.location.href
var url = new URL(url_string);
var globalVar = url.searchParams.get("value");
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}
If you want to hide the values you can use sessionStorage instead of query parameters:
function file2Function(getValue)
{
sessionStorage.setItem('value', getValue)
window.open("page2.html");
// window.open("https://www.google.com/");
}
function loadDynamicData()
{
var globalVar = sessionStorage.getItem('value')
var para=document.getElementById("paraId");
console.log(para);
para.innerText=globalVar+" : value from myFunction1 (Click Event)";
var secPage2 = document.getElementById("page2Section");
var headingJS2 = document.createElement("h4");
headingJS2.innerText=" This is dynamic heading";
secPage2.appendChild(headingJS2);
console.log(para);
}

How to get data from Google Spreadsheet to HTML as a javascript variable?

I am trying to create webapp with html service. Here is my code.
The code in code.gs file.
function doGet() {
return HtmlService
.createTemplateFromFile('userendhtml')
.evaluate();
}
function getData() {
var sss = SpreadsheetApp.openById('xxxx');
var rawData = sss.getDataRange().getValues()
var data = []
for (var i = 0; i< rawData.length; i++){
data.push(rawData[i])
}
return data
}
Now I want to access this data as javascript variable for further processing (for creating table with querying). The code in userendhtml.html is
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var data2 = getData();
</script>
</body>
</html>
This doesn't store data to variable data2. So how to get data from spreadsheet in variable in javascript?
You want to use google.script.run in conjunction with withSuccessHandler(...)
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
var data2;
google.script.run.withSuccessHandler(function(ret){
data2 = ret;
}).getData();
</script>
</body>
</html>
You could use the techniques found in the Templated Html reference that I gave you. But you could also do this:
<script>
var data2;
window.onload=function(){
google.script.run
.withSuccessHandler(function(dt){
data2=dt;
document.getElementById('myDiv').innerHTML=data2;
.getData();
}
</script>
The templated html approach loads on the server and this approach loads after the dom loads.
I just tested this example as a dialog
function dialogTest() {
var html='<div id="mydiv"></div>';
html+='<script>var data2;window.onload=function(){google.script.run.withSuccessHandler(function(dt){data2=dt;document.getElementById("mydiv").innerHTML=data2;}).getMtData();}</script>';
SpreadsheetApp.getUi().showModelessDialog(HtmlService.createHtmlOutput(html), 'Dialog Test');
}
function getMtData() {
return 'Hello World';
}

How to get this val(such as gLats in code) out of the function onComplete()?

This is the code that I want to work out, it's about AMap.com geolocation API. I want to know how to get this value (such as gLats in code) out of the function onComplete().
<!DOCTYPE html>
<html>
<head>
<title>amap</title>
<meta charset="utf-8">
<link rel="stylesheet" href="http://cache.amap.com/lbs/static/main1119.css"/>
<script type="text/javascript" src="http://webapi.amap.com/maps?v=1.3&key=key"></script>
<script type="text/javascript" src="http://cache.amap.com/lbs/static/addToolbar.js"></script>
</head>
<body>
<div id='container'></div>
<div id="tip"></div>
<div id="text"></div>
<div id="txt"></div>
<script type="text/javascript">
var map, geolocation;
map = new AMap.Map("", {
resizeEnable: true
});
map.plugin('AMap.Geolocation', function() {
geolocation = new AMap.Geolocation({
});
map.addControl(geolocation);
geolocation.getCurrentPosition();
AMap.event.addListener(geolocation, 'complete', onComplete);
AMap.event.addListener(geolocation, 'error', onError);
});
function onComplete(data) {
var str=['succsee'];
var gLngs=data.position.getLng();
var gLats=data.position.getLat();
str.push('longitude:' + data.position.getLng());
str.push('latitude:' + data.position.getLat());
document.getElementById('tip').innerHTML = str.join('<br>');
document.getElementById('text').innerHTML = str.join('<br>');
}
function onError(data) {
document.getElementById('tip').innerHTML = 'failure';
}
</script>
</body>
</html>
As I can see, you are already accessing the needed values in onComplete():
str.push('longitude:' + data.position.getLng());
str.push('latitude:' + data.position.getLat());
You cannot simply get them, onComplete is a callback that is called when the values are available. So do anything about them in onComplete, you may want to assingn them to global variables, etc, to have them easyly accessible from anywhere in code.
Assigning them to globals is the way to go.
//declare in the global scope
var gLats = null;
var gLngs = null;
...
function onComplete(data)
{
var str=['success'];
gLats=data.position.getLat();
gLngs=data.position.getLng();
...
}

Javascript/JSON error: not well formed

I am testing putting a text editor on my page and storing it as part of a JSON object.
HTML
<!DOCTYPE html>
<html>
<head>
<script src="http://tinymce.cachefly.net/4.0/tinymce.min.js" type="text/javascript"> </script>
<script type="text/javascript">
tinymce.init({
selector: "textarea"
});
</script>
<link rel="stylesheet" href="/jquery.mobile-1.3.2.min.css"/>
<script src="/jquery-1.9.1.min.js"></script>
<script src="/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>
<form method="post" action="formSubmit.js">
<textarea name ="editor"></textarea>
<p><input type="submit" value="Submit"></p>
</form>
</body>
</html>
JS
$(document).ready(function () {
var text = $("editor").val();
var name = "project name";
var id = 5;
var item = new item(name, text, id);
var itemArray = localStorage.items;
if (itemArray == undefined) {
itemArray = [];
} else {
itemArray = JSON.parse(itemArray);
}
itemArray.push(item);
localStorage.items = JSON.stringify(itemArray);
});
I want to be able to store item in a JSON object. When I run this I receive a "not-well formed" error at line 1 of the Javascript. It's a very simple program I'm running and can't seem to pinpoint what is causing the error. Is the JSON done incorrectly or are scripts in my HTML header causing issues?
$("editor") is looking for an html tag called 'editor'. you probably want to attach an id attribute to your and do $('#editor')

Categories