response.getselectedbutton() is not a function? - javascript

I am in school and trying to code a google apps script where I have a function bound to a doc with a custom menu that can create a new doc with the date, subject, and email it to the teacher of said subject. All was going according to plan until I decided to make it so that if I hit cancel instead of OK in one of the parameters I would get the default value of that parameter if I had not hit edit parameters so I could easily only change 1 or 2 things. The function works spotlessly, but now what's happening is I can't get the selected button for the alert that asks me if I want to edit parameters.
It just says
"TypeError: response.getSelectedButton is not a function"
and won't let me run my function. Here's my code for the function. This has worked fine for me in the past and I'm really not sure why it doesn't work now.
function Mathdoc() { var ui = DocumentApp.getUi();
var d = new Date();
var s = (d.getDate()) + '/' + (d.getMonth()+1) + '/' + d.getFullYear();
console.log(s);
var response = ui.alert( 'Change parameters?', ui.ButtonSet.YES_NO);
if (response.getSelectedButton() == ui.Button.YES) { insert all my other code here}
Is there a glitch or something I'm missing? I'm new to JS and fairly new to web design altogether.

There is no method named getSelectedButton(). The ui.alert() just returns the button and nothing else
function Mathdoc() {
var ui=DocumentApp.getUi();
var d = new Date();
var s = (d.getDate()) + '/' + (d.getMonth()+1) + '/' + d.getFullYear();
console.log(s);
var response=ui.alert( 'Change parameters?', ui.ButtonSet.YES_NO);
if (response==ui.Button.YES) { insert all my other code here}
Look at example here

Nope, this function doesn't exist. Basically if you type a function on google and don't find anything, it means the function doesn't exist
EDIT : If you have an error message that says it doesn't exist, it means that the function really doesn't exist or that the library containing the function is missing. But in your case the function doesn't exist

Related

Is it possible to read ExperimentId and VariationId in Javascript with Google Optimize?

I have created an A/B-test using Google Optimize. Now I would like to read the current experimentId and variationId in Javascript. My goal is to run different javascript based on the given variation.
I can't seem to find any info on this in the documentation. Is it possible?
Now there is also the Google Optimize javascript API available that is a better option:
The experimentId is now available in the Optimize UI, as soon as the experiment is created (before start).
The API is already available in the page and you can use it like this:
google_optimize.get('<experimentId>');
(note: this will work only after the Optimize container script has been loaded)
You can also register a callback to run the javascript that you want at any time (even before the Optimize script has been loaded) using:
function gtag() {dataLayer.push(arguments)}
function implementExperimentA(value) {
if (value == '0') {
// Provide code for visitors in the original.
} else if (value == '1') {
// Provide code for visitors in first variant.
}
gtag('event', 'optimize.callback', {
name: '<experiment_id_A>',
callback: implementExperimentA
});
If you want to find both the experimentId and variation you can register a callback for any experiment:
function implementManyExperiments(value, name) {
if (name == '<experiment_id_A>') {
// Provide implementation for experiment A
if (value == '0') {
// Provide code for visitors in the original.
} else if (value == '1') {
// Provide code for visitors in first variant.
...
} else if (name == '<experiment_id_B>') {
// Provide implementation for experiment B
...
}
gtag('event', 'optimize.callback', {
callback: implementManyExperiments
});
For more details
https://support.google.com/optimize/answer/9059383
EDIT: Nevermind my cookie-based answer below, I found a better solution.
Just do this:
var propertyId = "UA-1234567-33";
var experimentId = Object.keys(gaData[propertyId].experiments)[0];
var variationId = gaData[propertyId].experiments[experimentId];
Old answer:
(Don't do this.. keeping it here for reference)
Maximes answer is working but was not exactly what I was looking for. I wanted to be able to find the experimentId and variationId without adding code through the visual editor. I finally found a way.
The values are actually stored in the _gaexp cookie. The cookie is present when an experiment is running. You can inspect it in Chrome by opening Developer tools, going to the Application tab and clicking Cookies in the left pane. It looks something like this:
GAX1.2.S1SJOWxJTVO9tM2QKV3NcP.17723.1
The experiment id is the part after the second number:
S0SJOWxJTVO1tM2QKD2NcQ
The variation id is the last number:
1
I wrote this code to extract it from the cookie:
function getCookieValue(cookieName) {
var result = document.cookie.match('(^|;)\\s*' + cookieName + '\\s*=\\s*([^;]+)');
return result ? result.pop() : '';
}
function getExperimentId() {
var cookie = getCookieValue('_gaexp');
if (cookie == undefined) {
return undefined;
} else {
var fields = cookie.split('.');
return fields[2];
}
}
function getVariationId() {
var cookie = getCookieValue('_gaexp');
if (cookie == undefined) {
return undefined;
} else {
var fields = cookie.split('.');
return fields[4];
}
}
var experimentId = getExperimentId();
var variationId = getVariationId();
WARNING: Fetching the experiment ID and variationId from the cookie is not a good idea. For two reasons.
When the experiment is finished, the cookie is still present. The cookie is cached, so you will find an experimentId and variationId that does not apply, and you can not know if the experiment is running or not.
If you stop experiment A, and start experiment B, the old value for A will still be part of the cookie. So it will look something like this:
GAX1.2.S1SJOWxJTVO9tM2QKV3NcP.17723.1!vr1mB2L2RX6kSI1ZnUDTzT.18721.0
which is the same as how it would look if you were running to experiments at once. It makes it hard to reason about what experimentId to use.
Google Optimize allow you to run arbitrary JS on a per DOM element basis.
This feature is meant to modify the DOM elements, but there's nothing stopping you from using it to call a JS function or define some variables.
How to set up the script
Edit your experiment variant in the Visual Editor.
Click on the Select elements icon (the rectangle in the top left corner)
In the Element Selector field, type in body.
Click the Add change button and select Javascript. This will bring up a dialog that allows you to input a JS function that will be called for the body.
Put in the code you want to run in there.
What code to run
Assuming you have a doSomething() method define on your page, you can have your Google Optimized function look something like this:
doSomething("Experiment #1", "Variant A");
Alternatively, you can try defining your variables globally.
// We need to use `windows` here, because if we define a variable
// with `var`, it will be limited to the scope of the Google Optimize
// function.
window["google_optimize_exp_id"] = "Experiment #1";
window["google_optimize_exp_var_id"] = "Variant A";
If you use the second method, keep in mind that you need to wait until the Google Optimized function has run before running your own logic.
There are a 3 ways you could do this:
1) Depending on your Google Analytics setup, you can access the following object via Chrome console and pass in your GA property ID:
Object.keys(window.gaData["YOUR-GA-PROPERTY ID"].experiments).forEach(function(key, index){
var value = window.gaData["YOUR-GA-PROPERTY ID"].experiments[key];
console.log("Info", key, value, index);
});
2) As someone has already pointed out, you can access the _gaexp cookie, which stores your experiment ID and variant number.
//READ THE COOKIE
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
};
// GET THE COOKIE
let getCookie = readCookie("_gaexp");
console.log('getCookie', getCookie);
// WILL RETURN A STRING IN THIS FORMAT
// GAX1.2.YOUREXPERIMENTID.18803.0
// The long number in the middle is your experiment ID
// The number at the end is your variant number (0)
// SPLIT THE COOKIE
let splitCookie = readCookie("_gaexp").split("!");
// SPLIT THE COOKIE SO YOU CAN ACCESS THE EXPERIMENT ID AND VARIANT NUMBER
3) And lastly, you could use your dataLayer.
A bit more of a clunky way to do it, but in Optimize 360, you could add JavaScript in each variant, (when you go edit your AB Test/variants). And send your experiment ID to your dataLayer, as well as other information.
EG:
function returnDate() {
var today = new Date();
var dd = String(today.getDate()).padStart(2, '0');
var mm = String(today.getMonth() + 1).padStart(2, '0'); //January is 0!
var yyyy = today.getFullYear();
today = mm + '/' + dd + '/' + yyyy;
return today;
}
var dateToday = returnDate();
var ABTest = {
id: 'YOUREXPERIMENTID',
name: 'Title of your test',
description: 'Test description',
date: dateToday, //The launch date of AB Test.
variant: 1,
totalVariants: 5
};
// AND THEN PUSH ALL THAT INFORMATION INTO THE DATALAYER
dataLayer.Tests.push(ABTest);
Then to access all that information, all you need to do is access the window.dataLayer object.
Now how I've used google tag manager, add the "Test" key, in dataLayer.Tests. But of course you don't need that, but I just like to organise my object :)
I've found that the variant number can be obtained running a code like:
gaData["UA-XXXXXXXX-X"].experiments['ZYkOuNLKEoeLytt-dLWw3x']
The result should be "0"for the original, "1" for the first variant...
You can get the experiments with:
gaData["UA-XXXXXXXX-X"].experiments
Of course you have to replace UA-XXXXXXXX-X for the Google Analytics ID and ZYkOuNLKEoeLytt-dLWw3x for your experiment id.

Uncaught ScriptError: Invalid argument: EVENT_HANGOUT

This error is received when I try to update a calendar event's title and description. The strange thing is it works on one calendar and not on the other.
Here is a code example
function makeAppointment(eventID, person, calendarID){
Logger.log("eventID:", eventID);
Logger.log("userFolder: " + person);
Logger.log("calendarID: " + calendarID);
var userFolder = findFolder(person);
var calendar = CalendarApp.getCalendarById(calendarID);
var event = calendar.getEventSeriesById(eventID);
var appointments = getAppointments(true, calendarID);
try {
event.setTitle("Interviewee: " + person);
event.setDescription(userFolder.getUrl());
return appointments;
}
catch(e){
Logger.log("There was an issue with setting interview");
}
return appointments;
}
The makeAppointment function is called from the java script side where the relevant information is passed in. But it throws an error on the client side browser console image attached. There are 59 events present on the calendar that creates this issue and 2 on the one that doesn't, I find that to be the only difference between the two.
Thanks for any help provided in solving this issue
The issue was with the type of event. When creating an event, if there is a video call option present for that event, it will throw an error when updating. Removing the video call option will resolve the issue.

crm2011 plugin call js function

How can I run JavaScript function from appropriate web resource with a plugin in CRM2011.
I couldn't find any information on the Internet. Most of the resources describes how to trigger plugin from JS, but not opposite.
Here's JS code taht is copying the notes to the description field.
When save is clicked. you can see that the data is correctly display in a description field. However if you press save and close and open form again the description field will be empty.
I thought that the reason for that is that the JS executed after safe event but later tests descovered that it's false. Could someone point out an error in this JS code which cause that data is not saving?
Or give a suggestion how's write a plugin which is retrieving data from related entity and writes it into field in the form. thanx
function copyNotes()
{
// CLEAR DESCRIPTION FIELD
alert("JS");
Xrm.Page.getAttribute("description").setValue('');
// GET ID OF THE CASE AND CLEAN IT AND GET URL for oData stuff
//THEN CALL RETRIEVE FUNCTION
var caseID = Xrm.Page.data.entity.getId();
caseID = caseID.replace('{', '').replace('}', '');
var oDataPath = Xrm.Page.context.getServerUrl() + "/xrmservices/2011/organizationdata.svc";
ODataPath = Xrm.Page.context.getServerUrl() + "/XRMServices/2011/OrganizationData.svc";
retrieveRecord(caseID);
}
// CREATE AN HTTP REQUEST AND SEND IT
function retrieveRecord(Id) {
var retrieveReq = new XMLHttpRequest();
retrieveReq.open("GET", ODataPath + "/AnnotationSet?$filter=ObjectId/Id" + " eq (guid'" + Id + "')", true);
retrieveReq.setRequestHeader("Accept", "application/json");
retrieveReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
retrieveReq.onreadystatechange = function() {
// THIS HANDLES A CALLBACK
retrieveReqCallBack(this);
};
retrieveReq.send();
}
function retrieveReqCallBack(retrieveReq) {
if (retrieveReq.readyState == 4 /* complete */ )
{
if (retrieveReq.status == 200) {
//Success
var retrieved = this.parent.JSON.parse(retrieveReq.responseText).d;
// ITERATE THROUGH THE NOTES FOR THIS CASE
for (var i = 0; i < retrieved.results.length; i++) {
// IF IS AN EMPTY FIELD ADD 'case details:'
if (Xrm.Page.getAttribute("description").getValue() == null || Xrm.Page.getAttribute("description").getValue() == 'null') {
Xrm.Page.getAttribute("description").setValue('Case details:');
}
// BOF PARSE DATE
var date = retrieved.results[i].CreatedOn;
date = new Date(parseInt(date.replace("/Date(", "").replace(")/", ""), 10));
// EOF PARSE DATE
var newtext = "--------------------\r\n" + "Created by: " + retrieved.results[i].CreatedBy.Name + " - " + date + "\r\n" + retrieved.results[i].NoteText + "\r\n--------------------\r\n";
var text = Xrm.Page.getAttribute("description").getValue() + "\r\n" + newtext;
Xrm.Page.getAttribute("description").setValue(text);
}
}
}
}
There is no supported way to call back to the client from the server from within the plugin. I'm also not aware of any unsupported way.
I don't think this question even makes sense. Plugin's only trigger when there has been a CRUD operation of some sort. Any CRUD operation triggered by the GUI will result in a refresh of the entity any way. You could perform an update via javascript and an Odata call, but then once the plugin has finished, you can run whatever javascript you'd like to run.
There's no (reasonable) way to do that.
The reason for that is the fact that plugin is a server-size executed thingy. It can't even assume there's a GUI. (Of course, we know there is but generally, a server-size code can't interact with the GUI directly).
JavaScript is client-side code and a client assumes a server. That's (roughly) why JS can call a plugin (although I wouldn't put it that way) but not the other way around.
I've never had a need of such an operation so I'm curious as to what your task is. Are you asking of pure, academic interest or is it a part of a design? Perhaps there's a better way to reach your goal?

Having problems getting Javascript to work on SharePoint 2010

I was looking for help last week to get a simple javascript code made for SharePoint 2007 working for SharePoint 2010 and didn't really get a clear answer that i could use where i work unfortunately so i decided to try to just make my own. It's suppossed to be an Auction List and have a countdown in the "Time Left" field till the item expires, but i can't figure out what's wrong. I am very unfamiliar with javascript and sharepoint but i am an experienced programmer. Can anyone help with this? Here's the code below:
<script type="text/javascript">
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var lists = web.get_lists();
var listId = SP.ListOperation.Selection.getSelectedList();
var list = lists.getById(listId);
var item = getItemByName("End Date");
var end = Date.parse(item.text())/1000;
var todayNow = new Date();
todayNow = Date.parse(today)/1000;
var result = (end-todayNow);
var item2 = getItemByName("Time Left");
item2.text(result);
</script>
The End Date is a field that will probably be hidden, but just used as a placeholder to find the difference from now till the item expires.
Thanks guys for any responses.
Edit: Ok thanks Robert, you've really helped a lot. I was just about to post this when i saw your last comment. I'm extremely close now since I've been googling and researching what you said in your first comment and I've gotten this far:
<
script type="text/javascript">
ExecuteOrDelayUntilScriptLoaded(getWebSiteData, "sp.js");
var context = null;
var web = null;
var lists = null;
var listId = null;
var list = null;
var item = null;
function getWebSiteData(){
context = new SP.ClientContext.get_current();
web = context.get_web();
lists = web.get_lists();
listId = SP.ListOperation.Selection.getSelectedList();
list = lists.getById(listId);
context.load(list, 'End Date');
context.executeQueryAsync(Function.createDelegate
(this, this.onSuccessMethod), Function.createDelegate
(this, this.onFailureMethod));
}
function onSuccessMethod(sender, args){
alert('web title:' + web.get_title() + '\n ID:' + web.get_id
());
}
function onFailureMethod(sender, args){
alert('request failed' + args.get_message
() + '\n' + args.get_stackTrace());
}
</script>
I think the only thing i have left to do is figure out how to get the current item so i can set the Time Left for that specific item. Do you know how to do that? Am i as close as i think?
Thanks again for your help.
When you use javascript to access SharePoint, you're using the ECMA Client Object Model. I haven't worked with the Client Object Model for 07, but I have for '10, and right away can tell the code you posted won't work in sp10. At least in sp10 com, every time you grab a new instance of a SharePoint object (list, web, listItem, column, etc), you need to set that item into your local context, then load the context against the server via an asynchronous method. Only after that point, can you access the fields in the referenced object that you desire. Let me know if you cna't figure it out. Here's some sample code: http://pastebin.com/3amgaEhv
edit:
As for updating list items, I just found this link, here: http://sprider.org/2011/12/13/sharepoint-ecmascript-to-adddeleteupdateget-list-items/

How to display this JavaScript message in my webOS app?

I am writing a webOS app and I want the following code to present a "Good Morning!" message. What code do I need to put in my Main-scene.html file and what else do I need in the Main-assistant.js file to make this work?
Many thanks in advance.
MainAssistant.prototype.welcomeMessage = function(){
datetoday = new Date();
timenow = datetoday.getTime();
datetoday.setTime(timenow);
thehour = datetoday.getHours();
if (thehour > 18)
display = "Evening";
else
if (thehour > 12)
display = "Afternoon";
else
display = "Morning";
var greeting = ("Good " + display + "!");
document.write(greeting);
};
All the best
David
I don't know when the welcomeMessage method will be called, but if it's after the document has finished loading then it is closed. Calling document.write then will call document.open, which completely clears the document. Likely you have an element that the message should be written into, much better to use the load or DOMReady events (or whatever is available on WebOS).
Consider a much simpler form of the function and don't forget to declare variables to limit their scope to only what is necessary:
var tod = ['morning','morning','afternoon','evening'];
var now = new Date();
var greeting = 'Good ' + (tod[now.getHours()/6|0]) + '!';
If you want a library, try myLibrary. No, it's not my Library, it's your library when you use it. You can create a customised core and just the DOM ready part that is quite small and the code quality is excellent.

Categories

Resources