Passing GCLID and MSCKLID to Gravity Form form values - javascript

I'm trying to capture the GCLID and MSCKLID values from the URL, and pass them into the appropriate GF form fields. I found a way to pull them from the url, but I'm running into the DRY thing when trying to pass them into their field values.
Code that pulls them from the URL:
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi,
function(m,key,value) {
vars[key] = value;
console.log(value);
});
return vars;
}
var gclid = getUrlVars()["gclid"];
var mscklid = getUrlVars()["mscklid"];
Then this is the way I'm trying to pass them into the field values currently:
var selectorGCLID = "input[name='input_25']";
var selectorMSCKLID = "input[name='input_31']";
var fieldGCLID = document.querySelector(selectorGCLID);
var fieldMSCKLID = document.querySelector(selectorMSCKLID);
if(fieldGCLID) { fieldGCLID.value = gclid; }
if(fieldMSCKLID) { fieldMSCKLID.value = mscklid; }
What's a way where I can just check to see if the field selector is GCLID or MSCKLID, and then pass it to the appropriate field, instead of doing it 1x1 like this?

Can you just use the feature built into Gravity Forms to grab the URL parameter values?
If so, you can just go to the advanced tab of field 25 and click "Allow field to be populated dynamically" and then add: gclid. Go to field 31 and add: mscklid

Was able to capture UTM parameters without any add-on or coding by following these instructions: https://docs.gravityforms.com/using-dynamic-population/.
Added utm_source, utm_medium, utm_campaign as hidden fields and checked "Allow field to be populated dynamically" in the field settings.

Related

Populating table with textbox value from previous HTML page

I have some JS that stores the name and value of selected checkboxes on one page and then, on a button click, adds this data to a table on page 2.
This works, but now I am looking to do the same for a textbox containing a number. Specifically, I'm looking to take the value entered by the user and add this to a cell in the table. What would be the best way to approach this? Add to the existing function or create a separate on button click function specifically for the textbox value?
I have added a screenshot of the HTML table on page 2 along with where I would like the textbox value to go (highlighted with a red rectangle).
Here's what I have so far:
HTML for textbox (page 1):
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" name="numberofclicks" type="text" value="0" data-total="0" oninput="calculatetier()" />
</div>
JS on page 1:
$('#sales_order_form_button').click(function() {
let table_info = [];
$('input[type=checkbox]').each(
function(index, value) {
if($(this).is(':checked')) {
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
}
);
}
});
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
});
JS on page 2:
// Helper function
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
// actual code
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
for(let i = 0; i < data_from_page_1.length; i++){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text(data_from_page_1[i].name);
let recordValue = $("<td></td>").text(data_from_page_1[i].value);
row.append(recordName, recordValue);
$('#output_table').append(row);
}
// code to sum CPC column
var sum1 = 0;
$("#output_table tr > td:nth-child(2)").each(
(_,el) => sum1 += Number($(el).text()) || 0
);
$("#sum1").text(sum1);
//datetime stamp
var dt = new Date();
document.getElementById("datetime").innerHTML = dt.toLocaleString();
Output HTML table (page 2):
<table id="output_table">
<tr>
<th>Name</th>
<th>Value</th>
<th>Number of Clicks</th>
</tr>
<tfoot>
<tr>
<th id="total" colspan="1">Total CPC:</th>
<td id="sum1"></td>
</tr>
</tfoot>
</table>
As stated in the #Manu Varghese comment, the way to go would be using sessionStorage or localStorage.
First, let's differentiate both. According to the Stack Overflow question "HTML5 Local storage vs Session Storage", we have the following answer:
localStorage and sessionStorage both extend Storage. There is no difference between them except for the intended "non-persistence" of sessionStorage.
That is, the data stored in localStorage persists until explicitly deleted. Changes made are saved and available for all current and future visits to the site.
For sessionStorage, changes are only available per tab. Changes made are saved and available for the current page in that tab until it is closed. Once it is closed, the stored data is deleted.
Considering they are used the same way and you must to choose between what better fits your case, I will proceed using sessionStorage.
For that, in the first page you must use:
sessionStorage.setItem("key", "value")
You may set the item right when you perceives a change, like in the input 'blur' event.
and when you land in the second page (right when jQuery calls its start event), you will retrieve your data using:
sessionStorage.getItem("key")
Take in mind that localStorage/sessionStorage can support a limited amount of data. Even if that limit is way bigger than URL, most browsers will store only 2.5MB to 10MB per origin, according to the browser implementation (you may test by yourself in the link recommended in MDN (Mozilla Development Network), http://dev-test.nemikor.com/web-storage/support-test/).
Also, you may want to avoid storing sensitive data in the storages, due to some some discussions about security, which seems not to be a complaint here.
Implementation in the given case
Your code can be modified in three steps:
Change the way you save the data to use the storage
Creates a JSON of an object containing the array, instead the make the JSON using the array itself. Then you can add more fields.
Load the JSON object and its fields (the array and the number).
Step 1 - Changing to sessionStorage
Just now you have your Javascript on page 1 creating an array of data and stringifying that data to a JSON string.
If you want to use the storage rather than the URL for all the data, just change these lines of code from:
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
to the code that will save the data into a (local/session)Storage:
let jsonStr=JSON.stringify(table_info); // converts to JSON string
sessionStorage.setItem("oldData", jsonStr); // save to storage
window.location = "page2.html"; // navigate to other page
Notice that the storage can receive any string, but only strings, then we can remove the btoa function, but we must keep the stringify.
Step 2 -- Adding more data to save
Now you have one JSON that is an array of items. But what do you want is to include one more field, parallel to this array. Of course, you can't include it in the array, as it is a different thing. So, what we must to do is to create a JSON object which has a number field AND the array field itself.
Your function to create the array is all ok, then we will use the same "table_data" as the array and include it to a new JSON object:
let table_data = []; // the array you have
$('input[type=checkbox]').each(
... rest of code ...
); // the function that creates the array (I abbreviated it here)
// Creates an object with an array and a number
let jsonObj = {
table_data: table_data,
number_of_clicks: theNumberYouHave/* your variable with the number here */
};
// This is the bit above with CHANGES into variable names
// Instead of "table_data", now we save "jsonObj"
let jsonStr=JSON.stringify(jsonObj); // converts the "jsonObj" to a JSON string
sessionStorage.setItem("oldData", jsonStr);
window.location = "page2.html";
Remember to change "theNumberYouHave" to whatever your variable with the number is called. The you will append the number as a field of the JSON object.
In other words, this simply will create an structure like that:
{
number_of_clicks: 5216,
table_data: [
{ name: "...", value: "..."},
{ name: "...", value: "..."},
{ name: "...", value: "..."},
...
]
}
See? Your table_data is still there, but with a new sibling (number_of_clicks) inside an object.
Step 3 -- Loading data from page 1
For now, you have these two lines of code in page 2 to read data from page 1:
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
What do you need there, is to simply replace the getUrlParameter function to read from the storage, and remove the atob function to reflect the changes we made in page 1, this way:
let jsonObj = sessionStorage.getItem("oldData"); // reads the string
let data_from_page_1 = JSON.parse(jsonObj); // parse the JSON string
let table_data = data_from_page_1.table_data; // grab the table data
let number_of_clicks = data_from_page_1.number_of_clicks; // grab the number
Now you are free to use the variable "table_data" like you did, and to use the "number_of_clicks" in the way you want to use it. It is the number passed from page 1, then you may set it to your table cell.
You have it with the unique ID "sum1", the you may just:
$("#sum1").text(number_of_clicks);
And you are done!
I highly recommend localStorage and sessionStorage to be used, as per this and this
Page 1 code full source
$('#next_page_button').click(function(){
let table_info = [];
// Do for checkboxes
$('.campaignstrategy input[type=checkbox]').each(
function(index, value){
if($(this).is(':checked')){
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
type: 'checkbox'
}
);
}
});
$('.campaignstrategy input[type=text]').each(
function(index, value){
table_info.push(
{
name: $(this).attr('name'),
value: $(this).attr('value'),
type: 'text'
}
);
});
let base64str=btoa(JSON.stringify(table_info));
window.location = "page2.html?table_data=" + base64str;
});
Page 2 Code full source
// Helper function
function getUrlParameter(name) {
name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
var results = regex.exec(location.href);
return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
};
// actual code
let table_data = getUrlParameter('table_data');
let data_from_page_1 = JSON.parse(atob(table_data));
// clear table
$('#output_table').html("");
// generator checboxes
for(let i=0;i<data_from_page_1.length;i++){
if(data_from_page_1[i].type == "checkbox"){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text(data_from_page_1[i].name);
let recordValue = $("<td></td>").text(data_from_page_1[i].value);
let recordCount = $("<td></td>").text("");
row.append(recordName, recordValue, recordCount); // not used but needed
$('#output_table').append(row);
}
}
// generate textboxes
for(let i=0;i<data_from_page_1.length;i++){
if(data_from_page_1[i].type == "text"){
let row = $("<tr></tr>");
let recordName = $("<td></td>").text("");
let recordValue = $("<td></td>").text("");
let recordCount = $("<td></td>").text(data_from_page_1[i].value);
row.append(recordName, recordValue, recordCount);
$('#output_table').append(row);
}
}
ANSWER:
What would be the best way to approach this?
window.localStorage - stores data with no expiration date
window.sessionStorage - stores data for one session

Retrieve Google Sheets column by header name

Is there a way to retrieve a column dynamically by it's column name (header)?
Instead of:
var values = sheet.getRange("A:A").getValues();
Something like: (Just for simplicity)
var values = sheet.getRange(sheet.column.getHeader("name").getValues();
Please keep in mind that Google Apps Script is roughly ES3.
You can write one ;)
function getColValuesByName(sheet, name) {
var index = sheet.getRange(1,1,1,sheet.getLastColumn()).getValues()[0].indexOf(name);
index++;
return sheet.getRange(1,index,sheet.getLastRow(),1).getValues();
}
Here's a very simple one-line function you can copy. It returns the column number (A = 1, B = 2, etc.) for use in getRange, for example.
function getColByHeader(name) {
return SpreadsheetApp.getActiveSheet().getRange('1:1').getValues()[0].indexOf(name) + 1;
}
Although there is no direct way, there are plenty of ways to get what you want with a little set up:
Get all data and filter it(no set up):
var values = sheet.getDataRange().getValues();
var headers = values.splice(0,1);
headerIdx = headers[0].indexOf("name");
values = values.map(function(row){return [row[headerIdx]];})
Named ranges set up:
If you have named ranges associated with that column,
spreadsheet.getRangeByName('Sheet Name!name').getValues();//where 'name' is a named range
Developer metadata set up:
If you have developer metadata associated with that column,
SpreadsheetApp.getActive()
.createDeveloperMetadataFinder()
.withKey(/*METADATA_KEY_ASSOCIATED_WITH_COLUMN*/)
.find()[0]
.getLocation()
.getColumn()
.getValues();

query string value repeated while using forEach loop (javascript)

I am making a database website using AngularJs, mongodb, and restheart.
I design a table that if I input text in any of the five input area, the data with the keywords will show up.
<input types="text" ng-model="query.uniport_AC" ng-change="change()">
......
<input types="text" ng-model="query.site" ng-change="change()">
and in the javascript, my code is
$scope.change = function(){
var url = "";
angular.forEach($scope.query, function(value, key) {
if(!angular.isUndefined(value)){
url = url + "'"+key+"':{'$regex':'(?i)"+value+".*'},";
};
test = "http...&filter={" +url+ "}";
$http.get(test+"}").then(
function(res){
$scope.db = res.data._embedded["rh:doc"];
$scope.pages = res.data._total_pages;
$scope.sizes = res.data._size;
console.log(res);
},
function(err){
console.log(err);
}
);
My problem is, let say I input a and g in the first 2 input area, respectively, I wish to create a string like this
http...filter={'uniprot_AC':{'$regex':'(?i)a.*'},'gene_name':{'$regex':'(?i)g.*'},
However, I get a string like this
http...filter={'uniprot_AC':{'$regex':'(?i)a.*'},'uniprot_AC':{'$regex':'(?i)a.*'},'gene_name':{'$regex':'(?i)g.*'},'gene_name':{'$regex':'(?i)g.*'},
The url (let say 'uniprot_AC':{'$regex':'(?i)a.*'},) is repeated one more times. Can anyone point what is wrong with my code?

Creating Select Box from options stored in a variable

I want to create a select box from options stored in a variable (the values will change based on the user).
For now, I'm just trying to get it to work with this variable in my javascript file:
var resp = {"streams": [ {"sweet":"cookies"}, {"savory":"pizza"}]}
In the html file, I have a select id "selectedStream"
How do I invoke, both the select id from html and the variable from javascript to create the select box?
I've seen examples such as the one below, but I don't understand how to link the id and the variable to the box.
$("option:selected", myVar).text()
I hope this was coherent! Thanks
I think what you are trying to do is append option html nodes to an existing select element on your screen with an id of 'selectedStream'. You want to use the data from the 'resp' variable to populate the text and value of the option nodes that you are appending. If this is correct, I have implemented that functionality with this jsfiddle. The javascript is also below:
$(function(){
var resp = {"streams": [ {"sweet":"cookies", "savory":"pizza"}]};
var streamData = resp.streams[0];
var optionTemplate = "<option value=\"{0}\">{1}</option>";
for(var key in streamData){
var value = streamData[key];
var currentOptionTemplate = optionTemplate;
currentOptionTemplate = currentOptionTemplate.replace("{0}", key);
currentOptionTemplate = currentOptionTemplate.replace("{1}", value);
$("#selectedStream").append($(currentOptionTemplate));
}
});
Is that array necessary? If you're just trying to display the keys within that object I'd create a for loop:
var resp = { "streams": {"sweet": "cookies", "savory": "pizza"} }
for (property in resp.streams) {
$('#selectStream').append($('<option/>', {text: property, value: property}));
}
JSFiddle: http://jsfiddle.net/pWFNb/

doPost "unexpected error encountered" Web Form when submitting

I'm stuck on this web form after submitting. The below code worked in a previous web form I created with the help of Serge and a few others here some time ago. I'm attempting to re-purpose the code to make a PTO request web form. Right now, when submitting it spits out a "unexpected error encountered error and I'm lost on attempting to locate the issue. I'm thinking it may be how I've added panels together and their relationship? This is a work in progress, so i know clickhandlers will be added to provide response after submit etc. At the moment I'm looking to make sure it's passing entries in form to the spreadsheet. Thanks for any assistance.
//Setting the spreadshet ID and style of the form
var submissionSSkey = 'PUT YOUR KEY HERE'
var PanelStyle = {'background':'#c0d6e4','padding':'40px','borderStyle':'ridge','borderWidth':'15PX','borderColor':'#31698a'}
// Script-as-app template.
function doGet(e) {
//Creating the Appplication
var app = UiApp.createApplication();
//Creating panels to house the web form, instructional text, data pickers and setting style
var vertPanel = app.createVerticalPanel().setTitle('XYX Company PTO Request Form').setStyleAttributes(PanelStyle).setPixelSize(350,250);
var mainPanel = app.createFormPanel().setPixelSize(350,150);
var grid = app.createGrid(4,4).setId('ptogrid');
var ptoStart = app.createDateBox().setWidth('200').setName('ptoStartDate');
var ptoEnd = app.createDateBox().setWidth('200').setName('ptoEndDate');
var submitButton = app.createSubmitButton('<B>Submit</B>');
//Assigning widgets to the grid for positioning
grid.setText(1, 0, 'PTO Start Date')
.setWidget(1, 1, ptoStart)
.setText(2, 0, "PTO End Date")
.setWidget(2, 1, ptoEnd)
.setText(3, 0, '')
.setWidget(3, 1, submitButton)
//Instructions for completion of the PTO form by users.
vertPanel.add(app.createHTML("<b>PTO Request Form</b>"));
vertPanel.add(mainPanel);
vertPanel.add(app.createHTML("<br><b>Instructions:</b></br>" +
"<p>Select the starting date and the ending date for your PTO request. "+
"If you are taking a single day of PTO enter the starting and ending date as the same date. "+
"Click Submit once you've enter the dates. A request will be sent to your manager for reivew / approval.</p>"));
//Grabbing active users session information in order to look up user group assignment and manager
var employee = Session.getActiveUser().getEmail();
//Uses the UserManager class to get info by passing in the getActive user from base class
var userFirst = UserManager.getUser(Session.getActiveUser()).getGivenName();
var userLast = UserManager.getUser(Session.getActiveUser()).getFamilyName();
var wholeName = userFirst +" "+ userLast;
mainPanel.add(grid);
app.add(vertPanel);
return app;
}
function doPost(e) {
var app = UiApp.getActiveApplication();
var ptoStart = e.parameter.ptoStartDate;
var ptoEnd = e.parameter.ptoEndDate;
//var wholeName = e.parameter;
var timeStamp = new Date();
//Access spreadsheet store values
var sheet = SpreadsheetApp.openById(submissionSSkey).getSheetByName('PTO Requests');
var lastRow = sheet.getLastRow();
var targetRange = sheet.getRange(lastRow+1, 1, 1, 11).setValues([[timeStamp,ptoStart,ptoEnd]]);
app.close();
return app;
}
I'm pretty sure the error comes from the spreadsheet ID, the sheet name or the range definition, please double check these parameters and see if it solves the issue.
I checked on my account with wrong values and it generated the same issue you have, it works as expected with correct values.
Edit: your comment seems to confirm that...( didn't see it when I answered...)
Note: the error was easy to find by looking at the execution transcript in the script editor UI, it would even give you the line of code where the error occured.

Categories

Resources