Pushing Cookie Value Data to Hidden Fields - javascript

I recently installed a script that creates a Google __utmz cookie for my site visitors, and it sets all of the fields. Below is a look at it.
<script>
function get_campaign_info()
{
var utma = get_utm_value(document.cookie, '__utma=', ';');
var utmb = get_utm_value(document.cookie, '__utmb=', ';');
var utmc = get_utm_value(document.cookie, '__utmc=', ';');
var utmz = get_utm_value(document.cookie, '__utmz=', ';');
source = get_utm_value(utmz, 'utmcsr=', '|');
medium = get_utm_value(utmz, 'utmcmd=', '|');
term = get_utm_value(utmz, 'utmctr=', '|');
content = get_utm_value(utmz, 'utmcct=', '|');
campaign = get_utm_value(utmz, 'utmccn=', '|');
gclid = get_utm_value(utmz, 'utmgclid=', '|');
session_count = get_session_count(utma);
pageview_count = get_pageview_count(utmb, utmc);
if (gclid !="-") {
source = 'google';
medium = 'cpc';
}
}
</script>
Looking through my cookies I can see that it is being created. For example heres a bit of it:
"47664550.1486736628.2.2.utmcsr=website.com|utmccn=(referral)"
I have another script which is cleaning it all up and posting it to my console.
The issue that I am finding is that I can't figure out how to push those fields, like Campaign Medium, to hidden form fields on my site. Below is a look at how my typical Marketo form creates hidden fields with user data.
MktoForms2.whenReady(function(form){
ga(function(){
form.addHiddenFields({
GA_User_ID__c : ga.getByName('gtm1').get('userId')
});
});
Does anyone have an idea of how I can push medium, session, etc. to hidden fields? Thanks for any advice or just for reading! If it helps, the page I've been running tests on is powerreviews.com/form-test

For Marketo forms you should use the Marketo Form API. Go to this page and scroll down to the hidden field example.
In case the URL changes, here is the example code:
MktoForms2.loadForm("//app-sjst.marketo.com", "785-UHP-775", 1057, function (form) {
// Set values for the hidden fields, "userIsAwesome" and "enrollDate"
// Note that these fields were configured in the form editor as hidden fields already
form.vals({"userIsAwesome":"true", "enrollDate":"2014-01-01"});
});

Related

How to put the variable field names into the hidden fields on a FormAssembly form

We have two form tools for lead capture at my org and I'm trying to create a spreadsheet which uses the same formula to create the UTM parameter links to track our marketing campaigns with Google Analytics.
Example formula
=SUBSTITUTE(IF(LEFT(G4,1)="[","--",CONCATENATE(G4,IF(ISERROR(FIND("?",G4,1))=TRUE,CONCATENATE("?"),CONCATENATE("&")),IF(C4="","","estate="),IF(C4="","",C4),IF(A4="","","&utm_campaign="),IF(A4="","",A4),"&utm_medium=",H4,"&utm_source=",D4,IF(E4<>"-",CONCATENATE("&utm_content=",E4),),IF(E4<>"-",CONCATENATE("",$F$2),)))," ","%20")
On our Pardot pages I've applied the details outlined in https://jennamolby.com/how-to-use-utm-parameters-to-capture-lead-source-in-pardot/ and have these hidden fields populating correctly.
My trouble is with the FormAssembly form. I can change the above formula to include the FormAssembly ID's, ie tfa_199 replaces utm_medium and this works fine but then I would need my spreadsheet users to know which form tool is being used on that landing page. Is there a way to apply the same formula to both form tools and then using JavaScript populate the values for these hidden fields?
I've tried switching the Pardot JavaScript with the FormAssembly labels to no luck.
Sample link
https://www.tfaforms.com/4757457/?tfa_98=Test%20Estate%20X999&tfa_197=Fonzi&tfa_199=social&tfa_200=Facebook&tfa_198=Feed
// Parse the URL
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
// Give the URL parameters variable names
var source = getParameterByName('utm_source');
var medium = getParameterByName('utm_medium');
var campaign = getParameterByName('utm_campaign');
var term = getParameterByName('utm_term');
var content = getParameterByName('utm_content');
var estate = getParameterByName('estate');
// Put the variable names into the hidden fields in the form"
document.querySelector("tfa_200 input").value = source;
document.querySelector("tfa_199 input").value = medium;
document.querySelector("tfa_197 input").value = campaign;
document.querySelector("tfa_201 input").value = term;
document.querySelector("tfa_201 input").value = content;
document.querySelector("tfa_196 input").value = estate;
</script>
The ideal result is regardless of whether the form is a Pardot or FormAssembly the hidden fields populate the same using the same formula.
Have you tried this:
https://stackblitz.com/edit/js-hgrwkn
If your input fields have Ids:
<input type="text" id="utm_source" name="tfa_200"/>
and your hidden fields:
<input type="hidden" id="tfa_200" name="utm_source"/>
then:
<script>
document.getElementById('tfa_200').value =
document.getElementById('utm_source').name;
</script>
Then document.getElementById('tfa_200').name will contain utm_source.

Prevent form data from appearing in headers "Form Data" section by removing attribute?

I'm using accept.js which creates the object desired, but I'd like to also add another layer of protection by preventing the form data itself for the credit card posting. Specifically Id like to prevent it from appearing in the form data section as the thank you page loads. We don't want to send that information at all.
I've tried removing the name attribute, but that doesn't seem to work. It's possible I did this incorrectly.
This image shows form data headers on the success page which we post to. Again, we'd like to prevent that data from appearing here. Specifically the credit card data. https://imgur.com/0xVJ7Sw
I'm told this is possible and a good idea, but can't seem to figure out how to implement it. What we receive is the credit card number even though we've removed the name attribute on form submit.
// Create a connection between form and Authorize
Accept.dispatchData(secureData, function(res){
if(res.messages.resultCode === "Error"){
for(let i = 0; i < res.messages.message.length; i++){
console.log(res.messages.message[i].code + ": " + res.messages.message[i].text);
return false;
}
}else{
let opaqueData = res.opaqueData;
console.log("this prior to resetting values cardNumberE1.Value = ''; ============ " + cardNumberEl.value);
// clear out values before submitting
cardCodeEl.value = "";
cardNumberEl.value = "";
cardholderNameEl.value = "";
monthEl.value = "";
yearEl.value = "";
zipEl.value = "";
document.getElementById("input_28_52").value = opaqueData.dataDescriptor;
document.getElementById("input_28_53").value = opaqueData.dataValue;
console.log("this after resetting values cardNumberE1.Value = ''; ============ " + cardNumberEl.value);
console.log("this is the value of the hidden field opaqueData.dataDescriptor; ============ " + document.getElementById("input_28_52").value);
console.log("this is the value of the hidden field opaqueData.dataValue; ============ " + document.getElementById("input_28_53").value);
//cardholderNameEl = document.getElementById("input_28_26_5");
// We no longer need to send to our plugin, rely on GF plugin to send opaqueData
jQuery("#input_28_26_1").removeAttr('name');
console.log("end");
}
});

Fetching values from an element in an iframe on the same domain

I'm trying to condense two processes down in to one by having the two pages I need on one page using an iframe.
I have a page that contains a text area (used for sending an email) and then I have a purchase reference page that contains the details of someones purchase.
I'm trying to append an iframe of the purchase page to the bottom of my email page and then grab some data that's on it and insert it in to the text area.
EDIT: This is what I have so far:
Script one
//Grabs the selected purchase number
var purchaseNumber = window.getSelection();
purchaseNumber = purchaseNumber.toString();
var purchaseTitle;
var purchaseNumber;
function frameLoaded() {
purchaseTitle = window.frames['purchaseIframe'].contentDocument.getElementById ('listingTitle');
purchaseNumber = window.frames['purchaseIframe'].contentDocument.getElementById ('auctionSoldIdDisplay');
purchaseTitle = purchaseTitle.innerHTML;
purchaseNumber = purchaseNumber.innerHTML
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
}
if(purchaseNumber.length > 0){
var purchaseIframe = document.createElement('iframe');
purchaseIframe.src = 'http://www.mysite.co.nz/Admin/Listing/PurchaseDisplay.aspx?asid=' + purchaseNumber + '&submit1=++GO++';
purchaseIframe.setAttribute("height","1000");
purchaseIframe.setAttribute("width","100%");
purchaseIframe.setAttribute("id","purchaseIframe");
purchaseIframe.setAttribute("onload", "frameLoaded();");
void(document.body.appendChild(purchaseIframe));
alert(purchaseNumber);
}
Script Two
//Gather the selected template
var selectedTxt = document.getElementById('txtEmailText').value;
//Change the selected txt to a string
var insertText = selectedTxt.toString();
var purchaseTitle = window.frames['purchaseIframe'].contentDocument.getElementById ('listingTitle');
var purchaseNumber = window.frames['purchaseIframe'].contentDocument.getElementById ('auctionSoldIdDisplay');
purchaseTitle = purchaseTitle.innerHTML;
purchaseNumber = purchaseNumber.innerHTML
var purchaseDetails = purchaseTitle + " - " + purchaseNumber;
insertText = insertText.replace("PURCHASEDETAILS", purchaseDetails);
//Pasting the variable in to the textarea
document.getElementById('txtEmailText').value = insertText;
Effectively I am highlighting the purchase reference number on the page then executing this script to open the purchase page using the highlighted number. I am then grabbing the text values of the elements I need and pasting them in to the text area.
I'm still pretty new to javascript and am teaching myself as I go.
If i run the above scripts one after the other then it works like a charm, however if I try to run them together with the second in an onload() function set to the iframe then it won't.
Any help would be greatly appreciated or if you could point me in the direction of an article to help.
My first thought is that the iframe is not fully loaded before you try to get the values from it. My thought would be to try adding an onload event to your iframe and then when it loads invoke a function that grabs the value.
I would add purchaseIframe.setAttribute("onload", "frameLoaded();"); to your purchaseIframe block and then add the frameLoaded() function to your script. something like:
function frameLoaded() {
var purchaseTitle = window.frames[0].document.getElementById("listingTitle" );
var purchaseNumber = window.frames[0].document.getElementById("auctionSoldIdDisplay");
console.log(purchaseTitle.innerHTML);
console.log(purchaseNumber.innnerHTML);
}
And see if something like that grabs the right values. If it does than you can plug it in where you need it.
Am I understanding your problem correctly?

Execute JS in sharepoint display template

In my sharepoint list, I am dealing with items that should have attachments. I customized the template so that it would allow me to add attachments, but I see no possibilities to mark attachments as mandatory. I managed to check for attachments with the script
<script type="text/javascript" language="javascript">
function PreSaveAction()
{
var elm = document.getElementById("idAttachmentsTable");
if (elm == null || elm.rows.length == 0)
{
document.getElementById("idAttachmentsRow").style.display=&apos;none&apos;;
alert("Please attach Documents");
return false ;
}
else { return true ;}
}
</script>
but I was only able to use it in a custom form (not the template). Since the template is used for pretty much any interaction with the list, I want to use it and would like to execute the js code after the template has loaded. The template is referenced in between the tags <ZoneTemplate> and </ZoneTemplate>. There's much more code inside that form, but sharepoint-designer won't let me edit anything apart the stuff between those two tags.
It's really frustrating, because I seem to miss an obvious point. Hope I delivered enough information as I am not used to work with sharepoint and it's forms and templates for them...
When you need to add a JavaScript to a list form, you can browse to the form directly. For example, if your list is called MyList, then the new item form would be at http://url/Lists/MyList/newform.aspx and the edit form would be at EditForm.aspx. Browse to the page or pages where you want to insert your javascript code, then under Site Actions, click Edit Page. Add a Content Editor Web Part and either insert the javascript directly into the HTML of the content editor web part or add a link to an HTML file that has the javascript.
As for marking an attachment as mandatory, you may just need to include some wording to the form that will instruct the user to click Attach File button. Maybe something like this that would add a row to the bottom of the form table
<script type="text/javascript">
function addRow() {
var required = document.createTextNode("*");
var table = document.getElementsByClassName("ms-formtable")[0];
var tbody = table.getElementsByTagName("tbody")[0];
var tr = document.createElement("tr");
var td1 = document.createElement("td");
td1.setAttribute("class","ms-formlabel");
td1.setAttribute("vAlign","top");
var h31 = document.createElement("h3");
h31.setAttribute("class","ms-standardheader");
var text1 = document.createTextNode("Attachment");
h31.appendChild(text1);
var span1 = document.createElement("span")
span1.setAttribute("class","ms-formvalidation");
span1.setAttribute("title","This is a required field");
span1.appendChild(required);
h31.appendChild(span1);
var td1.appendChild(h31);
var tr.appendChild(td1);
var td2 = document.createElement("td");
td2.setAttribute("class","ms-formbody");
td2.setAttribute("vAlign","top");
var text2 = document.createTextNode("Click the Attach File button in the ribbon to add an attachment");
var td2.appendChild(text2);
var tr.appendChild(td2);
var tbody.appendChild(tr);
}
</script>
This is pretty ugly and can be simplified with jQuery.
<script type="text/javascript">
function addRow() {
var h3 = $('<h3 class="ms-standardheader">Attachment</h3>').append('<span class="ms-formvalidation">*</span>');
var td1 = $("<td></td>").append(h3);
var td2 = $("<td>Click the Attach File button in the ribbon to add an attachment</td>");
var tr = $("<tr></tr>").append(td1);
$(tr).append(td2);
$(".ms-formtable").first().find("tbody").first().append(tr);
}
</script>
Keep in mind this is untested and probably has some bugs in it.

global site variable js

I am new to javascript, i am trying to make a small site with two HTML pages (A and B) and a global js file.
So lets say i have selected certain items in page A, the list-preview on Page A gets updated.
But if i want to see the list in detail i have to go to page B.
Page A and B bith use the same .js file, the selected items are saved in a array.
How do i make sure the selected items still stay in the array, and the array doesn't get flushed when i go from page A to page B ?
what i thought of was ...
var selectedProductsName = new Array();
in OwnJS.js
the adding items to the preview list works.
i'm only struggling to keep the array unflushed when i go to page B from page A.
HTML5 introduces a new thing called localStorage. It's basically some kind of storage that is persistent between all pages of your website as well as between user sessions. It can be accessed as a simple key/value store:
var selectedProductsName = localStorage.getItem("selectedProductsName");
And to set:
localStorage.setItem("selectedProductsName", []);
Here's an article about getting started with localStorage, if you want to be able to do more things like checking browser compatibility for localStorage and watching the storage event, among others.
You could use the HTML5 local storage. It lets you tell the browser to save data on the user's machine. (There's also session storage, valid only for the current session.)
Save (in Apply.html)
IN.API.Profile("me")
.fields(["id", "firstName", "lastName", "pictureUrl","headline","industry","location:(name)","positions:(title)","emailAddress"])
.result(function(result) {
profile = result.values[0];
// save all keys to local storage
for (f in profile) localStorage[f] = fields[f];
// more stuff ...
});
to Retrieve (in personal_Info.html)
// retrieve first name from local storage
var firstName = localStorage["firstName"];
if (firstName !== undefined) {
$("#textfield1").attr(value, firstName);
}
Source Page
The Source Page has an HTML Button with a jQuery Click event handler. When the Button is clicked, the values of the Name TextBox and the Technology DropDownList is set as QueryString Parameter and then the page is redirected to the Destination page (Page2.htm).
<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
$(function () {
$("#btnQueryString").bind("click", function () {
var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
window.location.href = url;
});
});
</script>
Destination Page
On the Destination page (Page2.htm), inside the jQuery Page Load event handler the URL of the page is first checked to determine whether it has some QueryString Parameters being received, this is done by checking the window.location.search property. If it has some QueryString Parameters then loop is executed and each QueryString Key and Value Pair is inserted in an Array and finally the values are displayed on the page using the HTML span.
<script type="text/javascript">
var queryString = new Array();
$(function () {
if (queryString.length == 0) {
if (window.location.search.split('?').length > 1) {
var params = window.location.search.split('?')[1].split('&');
for (var i = 0; i < params.length; i++) {
var key = params[i].split('=')[0];
var value = decodeURIComponent(params[i].split('=')[1]);
queryString[key] = value;
}
}
}
if (queryString["name"] != null && queryString["technology"] != null) {
var data = "<u>Values from QueryString</u><br /><br />";
data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
$("#lblData").html(data);
}
});
</script>

Categories

Resources