I have google custom search box (Javascript) in my website.
with following code:
<script type="text/javascript">
var searchTerm = "";
google.load('search', '1', { language: 'en' });
google.setOnLoadCallback(function() {
var customSearchControl = new google.search.CustomSearchControl('XXXXX');
customSearchControl.draw('cse');
customSearchControl.execute('<%= Request.QueryString["search"] %>');
customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
}, true);
</script>
When user clicks on one of the results and on the target page clicks on Browser's back button, an empty search screen appears.
Is it possible to keep the results page when getting back to the search page?
Also I would like to retrieve the search term from this script, how can I do that?
Thanks in advance
This is the API of google CSE:
https://developers.google.com/custom-search/docs/js/cselement-devguide
Here you can see a custom query working:
https://code.google.com/apis/ajax/playground/#custom_search_control
and this is how you retrieve the query:
https://code.google.com/apis/ajax/playground/#show_search_query
Using rafael's suggestion I came with following solution for my problem:
<script type="text/javascript">
var searchTerm = "";
if (sessionStorage.getItem("googleSearchTerm") != '')
searchTerm = sessionStorage.getItem("googleSearchTerm");
runGoogleSearch(searchTerm);
function runGoogleSearch(searchTerm) {
google.load('search', '1', { language: 'en' });
google.setOnLoadCallback(function () {
var customSearchControl = new google.search.CustomSearchControl('XXXXXX');
customSearchControl.draw('cse');
customSearchControl.execute(searchTerm);
// Set a callback so that whenever a search is started we will call searchStart
customSearchControl.setSearchStartingCallback(this, searchStart);
customSearchControl.setLinkTarget(google.search.Search.LINK_TARGET_SELF);
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET);
}, true);
}
// Whenever a search starts, alert the query.
function searchStart(searchControl, searcher, query) {
sessionStorage.setItem("googleSearchTerm", "");
var content = document.getElementById('content');
var queryDiv = document.getElementById('query');
if (!queryDiv) {
var queryDiv = document.createElement('div');
queryDiv.id = 'query';
document.body.appendChild(queryDiv);
}
//queryDiv.innerHTML = "User searched for: " + query;
sessionStorage.setItem("googleSearchTerm", query);
//alert(sessionStorage.getItem("googleSearchTerm") + " gozo");
}
</script>
Related
I'm would like to do a 2 step process without the user knowing. Right now when the user click on the link from another page.
URL redirect to run some JavaScript function that updates the database.
Then pass the variable to view a document.
User clicks on this link from another page
Here is some of code in the JavaScript file:
<script type="text/javascript">
window.onload = function(){
var auditObject ="";
var audit_rec = {};
var redirLink = "";
if(document.URL.indexOf('?1w') > -1 {
redirLink = "https://www.wikipedia.org/";
auditObject = redirLink;
audit_rec.action = "OPEN";
audit_rec.object = auditObject;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
window.open(redirLink);
} else {
audit_rec.target = /MyServlet;
audit_rec.action = "OPEN";
audit_rec.object = TESTSITE;
audit_rec.object_type = "WINDOW";
audit_rec.status = "Y";
}
function audit(audit_rec) {
var strObject = audit_rec.object;
strObject = strObject.toLowerCase();
var strCategory = "";
if (strObject.indexOf("wiki") > -1) {
strCategory = "Wiki";
} else if strObject.indexOf("test") > -1) {
strCategory = "TEST Home Page";
}
//Send jQuery AJAX request to audit the user event.
$.post(audit_rec.target, {
ACTION_DATE : String(Date.now()),
DOMAIN : "TESTSITE",
ACTION : audit_rec.action,
OBJECT : audit_rec.object,
OBJECT_TYPE : audit_rec.object_type,
STATUS : audit_rec.status
});
}
//TEST initial page load.
audit(audit_rec);
}
</script>
Can someone help? Thanks
You could give your link a class or ID such as
<a id="doclink" href="http://website.com/docviewer.html?docId=ABC%2Fguide%3A%2F%2F'||i.guide||'">'||i.docno||'</a>
then use javascript to intercept it and run your ajax script to update the database. Here's how you'd do it in jQuery:
$('#doclink').click(function(e) {
var linkToFollow = $(this).attr('href');
e.preventDefault();
yourAjaxFunction(parameters, function() {
location.href = linkToFollow;
});
});
where the function containing the redirect is a callback function after your ajax script completes. This stops the link from being followed until you've run your ajax script.
if your question is to hide the parameters Here is the Answer
you just use input type as hidden the code like this
'||i.docno||'
I'm using the following code to get google contacts name and phone number. Authorization page itself is not coming properly it shows error as "The page you requested is invalid". :( pls help me to solve this...
`
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("gdata", "1.x");
var contactsService;
function setupContactsService()
{
contactsService = new google.gdata.contacts.ContactsService('exampleCo-exampleApp-1.0');
}
function logMeIn() {
var scope = 'https://www.google.com/m8/feeds';
var token = google.accounts.user.login(scope);
}
function initFunc() {
setupContactsService();
logMeIn();
getMyContacts();
}
function checkLoggedIn(){
scope = "https://www.google.com/m8/feeds";
var token = google.accounts.user.checkLogin(scope);
if(token != "")
return true;
else
return false;
}
function getMyContacts() {
var contactsFeedUri = 'https://www.google.com/m8/feeds/contacts/default/full';
var query = new google.gdata.contacts.ContactQuery(contactsFeedUri);
//We load all results by default//
query.setMaxResults(10);
contactsService.getContactFeed(query, handleContactsFeed, ContactsServiceInitError);
}
//Gets the contacts feed passed as parameter//
var handleContactsFeed = function(result) {
//All contact entries//
entries = result.feed.entry;
for (var i = 0; i < entries.length; i++) {
var contactEntry = entries[i];
var telNumbers = contactEntry.getPhoneNumbers();
var title = contactEntry.getTitle().getText();
}
}
</script>
<body>
<input type="submit" value="Login to Google" id="glogin" onclick="initFunc();">
</body>`
Thanks
It looks like you are trying to use the Google Contacts 1.X API. That's been deprecated. Look at the JavaScript examples for the Google 3.X API and see if that helps.
You can try this example
var config = {
'client_id': 'Client ID',
'scope': 'https://www.google.com/m8/feeds'
};
inviteContacts = function() {
gapi.auth.authorize($scope.config, function() {
fetch(gapi.auth.getToken());
});
}
function fetch(token) {
$.get("https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json", function(response) {
console.log(response);
//console.log(response.data.feed.entry);
});
}
Don't forget to add <script src="https://apis.google.com/js/client.js"></script> into your html file. Good Luck!
Getting some odd behavior from google custom search that I can't seem to suss out. Maybe someone has a clue.
I'm putting together a Magento site, which has its own internal search engine - but is limited to product only. I want to implement google custom search results on the search results page as well. I figure I should be able to simply execute a search based on the query vars in the url (to return all the non-product content), as such:
<section style="min-height:600px">
<div style="background-color:#DFDFDF; min-height:800px; width:100%;">
<div id="cse">Loading</div>
</div>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
$(document).ready( function(){
console.log('search initiated');
var t = window.setTimeout( function(){ customSearch(); }, 5000 );
});
function customSearch(){
var q = urlParams()['q'];
if (q != undefined && q != ""){
console.log('q : %s', q); //outputs successfully
google.load('search', '1');
google.setOnLoadCallback(function () {
var customSearchControl = new google.search.CustomSearchControl(MY CUSTOM ID KEY);
var cseDrawOptions = new google.search.DrawOptions();
cseDrawOptions.setAutoComplete(true); //unknown if this is required...
customSearchControl.draw('cse',cseDrawOptions);
customSearchControl.execute(q);
}, true);
}
}
function urlParams(){
var vars = [];
var hash;
var index = window.location.href.indexOf('?');
if( index != -1 ){
var hashes = window.location.href.slice(index + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1].replace(/\+/g, " ");
}
}
return vars;
}
//]>
</script>
</section>
I'll note that I've pulled all other content out of the logic (but its implementation in magento is identical).
So the behavior goes like this: page loads fine (I'm delaying the google search with a timeout for testing purposes ). Assuming there is a query var in the url the console traces out as expected. Then the page just gets wiped out, with no content back from google. "Wiped out"... meaning all elements on teh page disappear, or are getting overwritten by a new page that google loads. As if the search control isn't creating an iframe - its just replacing the page with a <body>-less html page.
I've ready a number of articles on the subject, and gone over the API - this code looks like it should work. But clearly isn't.
What am I missing?
Cheers -
UPDATE
Continued messing around with this has revealed that for whatever reason :
google.load('search', '1');
google.google.setOnLoadCallback( console.log('loaded') )
Was the cause of the replaced page issue. The responded page, however contained links to the search module that google is hosting. And if I manually linked those files (forgoing a google.load) then I could run a search as expected:
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<script src="http://www.google.com/uds/?file=search&v=1" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
... search logic
Then I found an alternate syntax on the google developers page that seemed to work as expected:
$(document).ready( function(){
google.load("search", "1", {"callback" : customSearch});
});
function customSearch(){
var q = urlParams()['q'];
if (q != undefined && q != ""){
var cseControl = new google.search.CustomSearchControl('MY CUSTOM KEY');
var cseDrawOptions = new google.search.DrawOptions();
cseDrawOptions.enableSearchResultsOnly()
cseControl.draw('cse', cseDrawOptions);
cseControl.execute(q);
}
}
Which works as expected. Only real problem at this point is the host of
Unsafe JavaScript attempt to access frame with URL http://mydomain from frame with URL http://www.google/cse?...
That now gets thrown.
I don't know how the two different versions of load syntax changes anything... but it seemed to of. Whatever the case, I'm unclear as to how to resolve these cross domain errors.
Thoughts would be great.
Nothin huh?
Well - I've basically worked out a good solution, using an alternate method that I think will be more flexible in the long run. Using googles RESTful API and simple jquery .ajax call, I can obtain good, controllable results with no cross-domain errors:
<div id="cse">Loading</div>
<script>
//https://developers.google.com/custom-search/v1/getting_started
//https://developers.google.com/custom-search/v1/using_rest#query-params
//https://developers.google.com/custom-search/v1/cse/list
var _url = "https://www.googleapis.com/customsearch/v1";
var _key = 'AIzaSy... your api key here';
var _cx = '001809... your engine id';
var _q = urlParams()['q']; //query param
jQuery(document).ready(function() {
$j.ajax({
url : _url,
type : 'GET',
dataType : 'jsonp',
data :{
key : _key,
cx : _cx,
q :_q
},
success : function(data, textStatus, jqXHR){ responseHandler(data); },
error : function(jqXHR, textStatus, errorThrown){ console.log('error: %s'), errorThrown},
beforeSend : function(){ console.log('sending request')},
crossDomain : true
});
});
function responseHandler( response, status) {
console.log(response);
var cse = $j('#cse'); // render vars as needed...
for (var i = 0; i < response.items.length; i++) {
var item = response.items[i];
cse.append( "<br>" + item.htmlTitle);
}
}
function urlParams(){
var vars = [];
var hash;
var index = window.location.href.indexOf('?');
if( index != -1 ){
var hashes = window.location.href.slice(index + 1).split('&');
for(var i = 0; i < hashes.length; i++){
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
}
return vars;
}
</script>
And you can too;D
Cheers
I can get the code to pop-up both alert but redirecting is not working. After adding an item it should redirect.
<script type="text/javascript" src="/_layouts/jquery/jquery-1.3.2.min.js"></script>
<script type="text/javascript">
fields = init_fields();
// Where to go when cancel is clicked
goToWhenCanceled = '/test/English/YouCanceled.aspx';
// Edit the redirect on the cancel-button's
$('.ms-ButtonHeightWidth[id$="GoBack"]').each(function(){
$(this).click(function(){
STSNavigate(goToWhenCanceled);
})
});
// Edit the form-action attribute to add the source=yourCustomRedirectPage
function setOnSubmitRedir(redirURL){
var action = $("#aspnetForm").attr('action');
var end = action.indexOf('&');
if(action.indexOf('&')<0){
newAction = action + "?Source=" + redirURL;
}else{
newAction = action.substring(0,end) + "&Source=" + redirURL;
}
$("#aspnetForm").attr('action',newAction);
alert(redirURL);
}
/*
// Use this for adding a "static" redirect when the user submits the form
$(document).ready(function(){
var goToWhenSubmitted = '/test/English/ThankYou.aspx';
setOnSubmitRedir(goToWhenSubmitted);
});
*/
// Use this function to add a dynamic URL for the OnSubmit-redirect. This function is automatically executed before save item.
function PreSaveAction(){
// Pass a dynamic redirect URL to the function by setting it here,
// for example based on certain selections made in the form fields like this:
var dynamicRedirect = '/surveys/Pages/ThankYou.aspx';
// Call the function and set the redirect URL in the form-action attribute
setOnSubmitRedir(dynamicRedirect);
alert(dynamicRedirect);
// This function must return true for the save item to happen
return true;
}
function init_fields(){
var res = {};
$("td.ms-formbody").each(function(){
if($(this).html().indexOf('FieldInternalName="')<0) return;
var start = $(this).html().indexOf('FieldInternalName="')+19;
var stopp = $(this).html().indexOf('FieldType="')-7;
var nm = $(this).html().substring(start,stopp);
res[nm] = this.parentNode;
});
return res;
}
</script>
If you set window.location.href = 'SomeUrl' at any point, it should redirect right then. Looking at your code, I dont see that anywhere.
At what point are you trying to redirect?
Google Adwords offers no code to add to your page to count a conversion if somebody clicks on a link. But as it's Javascript, I am sure there is a way to do this.
Here's the code (unaltered) Google gives you to include in the page, that should count as a conversion (most of the time a thank you page):
<!-- Google Code for Klick Conversion Page -->
<script type="text/javascript">
<!--
var google_conversion_id = 1062751462;
var google_conversion_language = "de";
var google_conversion_format = "1";
var google_conversion_color = "ffffff";
var google_conversion_label = "dKXuCODvugEQ5pnh-gM";
var google_conversion_value = 0;
//-->
</script>
<script type="text/javascript" src="http://www.googleadservices.com/pagead/conversion.js">
</script>
<noscript>
<div style="display:inline;">
<img height="1" width="1" style="border-style:none;" alt="" src="http://www.googleadservices.com/pagead/conversion/1062751462/?label=dKXuCODvugEQ5pnh-gM&guid=ON&script=0"/>
</div>
</noscript>
With other conversion tracking scripts some function has to be executed to count the conversion. Here, just adding the JS-File to your page can be enough to trigger the conversion-tracking, as conversion.js calls a function on load (download it and look at it after running it through a code beatuifier, it's really quite nice work!).
Any idea how to tackle this?
Don't know if you've already found it... I mention it anyway for future surfers...
I was looking for the same, and found this piece of code :
<script type="text/javascript">
function trackConv(google_conversion_id, google_conversion_label) {
var image = new Image(1, 1);
image.src = "//www.googleadservices.com/pagead/conversion/" + google_conversion_id + "/?label=" + google_conversion_label + "&script=0";
}
</script>
Then for links which you want to track just do this :
<a onclick="trackConv(1234567890, 'LQV8CNq6RxCKlPbvAw');" href="http://www.example.com">Link</a>
It appears that Google now offers an onclick option that you can copy and paste from the Conversions page in AdWords. From the AdWords Conversions page:
Add the tag to a button on your website, such as a "Buy now" button.
Here's a snippet from the page of documentation entitled Track clicks on your website as conversions. Replace XXXXX with conversion ID and label:
<!-- Google Code for Conversion Page
In your html page, add the snippet and call
goog_report_conversion when someone clicks on the
chosen link or button. -->
<script type="text/javascript">
/* <![CDATA[ */
goog_snippet_vars = function() {
var w = window;
w.google_conversion_id = XXXXXXX;
w.google_conversion_label = "XXXXXXX";
w.google_remarketing_only = false;
}
// DO NOT CHANGE THE CODE BELOW.
goog_report_conversion = function(url) {
goog_snippet_vars();
window.google_conversion_format = "3";
var opt = new Object();
opt.onload_callback = function() {
if (typeof(url) != 'undefined') {
window.location = url;
}
}
var conv_handler = window['google_trackConversion'];
if (typeof(conv_handler) == 'function') {
conv_handler(opt);
}
}
/* ]]> */
</script>
<script type="text/javascript"
src="//www.googleadservices.com/pagead/conversion_async.js">
</script>
And somewhere else in your code
button.addEventListener('click', function() {
console.log('Button clicked!');
goog_report_conversion();
});
I've a similar problem.
The Problem:
My client have a contact page that have a form. After the user fill all the form fields, there is a validation(to check if the user filled correctly all the fields). After the validation, the user is redirected to the webmail server page. There isn't an "Success" or "Thank You" page. So i needed to put the Adwords tag, after the form validation.
The Solution:
The validation was done this way:
var missinginfo = "";
var f = document.forms["CONTACT"];
if (f.name.value == ""){
missinginfo += "\n - name";}
.
.
.
if (missinginfo != "")
{
missinginfo ="_____________________________\n" +
"Empty Field" + "incorrectly filled" +
missinginfo + "\n_____________________________"
alert(missinginfo);
return false;
}
//End of Validation
So i added this snippet code:
else if(missinginfo == ""){ //Check if the form was filled correctly
adw_conv(); //Function Name
return false;
}
function adw_conv(){
var img = new Image() //Creates an image using JS to make the request
img.src = "http://www.googleadservices.com/pagead/conversion/123456789/?label=-8bcaCNHv6AIQl_v8_QM&guid=ON&script=0";
img.onload = function(){
var form = document.getElementsByName('CONTACT')[0];
form.submit();
}}
This way, after the form validation and before the website redirect the user to the webmail page, is triggered the Adwords Conversion!
Google Conversion Tracking concept using Ajax on a submit button :
$.ajax({
type: "POST",
url: "enquiry-submit.php",
data: data,
success: function (result) {
$("#msg").fadeIn(400).html(result);
/* Conversion Tracking Start */
var google_conversion_id = YOUR_CONVERSION_ID_HERE;
var google_conversion_language = "en";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "YOUR_CONVERSION_LABEL_HERE";
var google_remarketing_only = false;
$.getScript('//www.googleadservices.com/pagead/conversion.js');
var image = new Image(1, 1);
image.src = "//www.googleadservices.com/pagead/conversion/YOUR_CONVERSION_ID_HERE/?label=YOUR_CONVERSION_LABEL_HERE&guid=ON&script=0";
/* Conversion Tracking End */
}
});
It is 100% working on my Google Ads Campaign.
Note: You must Test this by clicking on your ad. The effect of conversion will be visible after 12 minute on your AdWords Console
Add the code below to the section of the page you want to track conversions on.
<script>
function adwTrack() {
var img = new Image(1,1);
img.src = "https://www.googleadservices.com/pagead/conversion/XXXXXXXXXX/?value=1.00¤cy_code=EUR&label=XXXXXXXXXX&guid=ON&script=0";
}
Just replace the XXX… with your actual conversion id and label.
Then call the adwTrack() function we created above in your link’s onclick event:
Track This
You can also do this using GTM: https://www.redflymarketing.com/blog/track-conversions-without-a-thank-you-page/