How to pass UTM info to form submit? - forms

Bottom line, I want to know exactly which leads (form submissions) came through Adwords.
It's a manually built form (no JotForm or anything) and submits through manually built php that, at the moment) sends me an Email. The page and form itself is HTML.
So we can add UTM info to the Adwords URLs, and I'm looking for a way to grab that UTM information and pass it on to the Email (like through a hidden field in the form or something.)
I think this would be the easiest way to make sure we know which leads we paid for, but if not, please let me know of a better way.
TIA

The best way to track these utm is to store them into a js cookie and then retrieve them to store values into hidden fields in form.
using cookies will allow you to navigate through different pages without having to pass the data again and again in the url.
You can modify this solution to use for your form.
http://www.decorumsol.com/tracking-utm-parameters-in-contact-form-7/
Edit:
Here is the code for better understanding.
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
jQuery(document).ready(function() {
jQuery('form').find('input.utm_source').each(function() {
var a = getQueryVariable('utm_source');
if(a){
jQuery(this).val(a);
}
});
jQuery('form').find('input.utm_medium').each(function() {
var a = getQueryVariable('utm_medium');
if(a){
jQuery(this).val(a);
}
});
jQuery('form').find('input.utm_campaign').each(function() {
var a = getQueryVariable('utm_campaign');
if(a){
jQuery(this).val(a);
}
});
jQuery('form').find('input.utm_term').each(function() {
var a = getQueryVariable('utm_term');
if(a){
jQuery(this).val(a);
}
});
jQuery('form').find('input.utm_content').each(function() {
var a = getQueryVariable('utm_content');
if(a){
jQuery(this).val(a);
}
});
});
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
document.cookie = name+"="+value+expires+"; path=/";
}
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;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
var c_name = "_aaa_utmz";
if(getQueryVariable("utm_source") != "") {
createCookie("_aaa_utmz", getQueryVariable("utm_source") + "|" + getQueryVariable("utm_medium")+ "|" + getQueryVariable("utm_term")+ "|" + getQueryVariable("utm_campaign")+ "|" + getQueryVariable("utm_content"), 60);
}
else if (readCookie(c_name)){
c_start=readCookie(c_name);
var _pipe = c_start.split("|");
jQuery("input[name=utm_source], .utm_source").val(_pipe[0]);
jQuery("input[name=utm_medium], .utm_medium").val(_pipe[1]);
jQuery("input[name=utm_term], .utm_term").val(_pipe[2]);
jQuery("input[name=utm_campaign], .utm_campaign").val(_pipe[3]);
jQuery("input[name=utm_content], .utm_content").val(_pipe[4]);
}
in your html form, create
<div style="display:none;">
<input type="text" value="" class="utm_source" name="utm_source" />
<input type="text" value="" class="utm_medium" name="utm_medium" />
<input type="text" value="" class="utm_term" name="utm_term" />
<input type="text" value="" class="utm_campaign" name="utm_campaign" />
<input type="text" value="" class="utm_content" name="utm_content" />
</div>

Related

How do I rename files uploaded to an apps script web app form?

I've made a little web app form by splicing together some code I found. It works nearly perfectly for me, allowing me to upload files to a Google Drive folder, logging the data submitted in the form in a spreadsheet and emailing me when a file is uploaded.
However, what I really want to be able to do is to rename the files that are uploaded according to the form data. For example, if the inputted manufacturer value = "Sony" and the date value = 12-04-2016, then make the filename "Sony_12-04-2016.pdf"
From looking it up as best I can it seems I need to pass the submitted values into the createFile() function but I'm quite new to coding and not really sure what I'm doing here..
Here's what I have so far:
.gs
var TO_ADDRESS = "my email address";
function doGet(e) {
return HtmlService.createTemplateFromFile('index')
.evaluate()
.setTitle('Price List Upload Form')
}
function processForm(theForm) {
var fileBlob = theForm.fileUpload;
Logger.log("fileBlob Name: " + fileBlob.getName())
Logger.log("fileBlob type: " + fileBlob.getContentType())
Logger.log('fileBlob: ' + fileBlob);
var fldrSssn = DriveApp.getFolderById('my Google Drive folder id');
fldrSssn.createFile(fileBlob);
return true;
}
function formatMailBody(obj) {
var result = "";
for (var key in obj) {
result += "<h4 style='text-transform: capitalize; margin-bottom: 0'>" + key + "</h4><div>" + obj[key] + "</div>";
}
return result;
}
function doPost(e) {
try {
Logger.log(e);
record_data(e);
var mailData = e.parameters;
MailApp.sendEmail({
to: TO_ADDRESS,
subject: "New Price List Uploaded",
htmlBody: formatMailBody(mailData)
});
return ContentService
.createTextOutput(
JSON.stringify({"result":"success",
"data": JSON.stringify(e.parameters) }))
.setMimeType(ContentService.MimeType.JSON);
} catch(error) {
Logger.log(error);
return ContentService
.createTextOutput(JSON.stringify({"result":"error", "error": e}))
.setMimeType(ContentService.MimeType.JSON);
}
}
function record_data(e) {
Logger.log(JSON.stringify(e));
try {
var doc = SpreadsheetApp.getActiveSpreadsheet();
var sheet = doc.getSheetByName('responses');
var headers = sheet.getRange(1, 1, 1, sheet.getLastColumn()).getValues()[0];
var nextRow = sheet.getLastRow()+1;
var row = [ new Date() ];
for (var i = 1; i < headers.length; i++) {
if(headers[i].length > 0) {
row.push(e.parameter[headers[i]]);
}
}
sheet.getRange(nextRow, 1, 1, row.length).setValues([row]);
}
catch(error) {
Logger.log(e);
}
finally {
return;
}
}
.html
<form id="gform" autocomplete="on" method="POST" class="pure-form pure-form-stacked"
action="script url" onsubmit="picUploadJs(this)">
<fieldset class="pure-group">
<input name="fileUpload" type="file" />
</fieldset>
<fieldset class="pure-group">
<label for="manufacturer">Manufacturer: </label>
<input id="manufacturer" name="manufacturer" type="text" placeholder="Manufacturer Name" required/>
</fieldset>
<fieldset class="pure-group">
<label for="issueDate">Date Issued: </label>
<input id="issueDate" name="issueDate" type="date" required />
</fieldset>
<fieldset class="pure-group">
<label for="info">Additional Info: </label>
<input id="info" name="info" type="text" placeholder="Any Additional Information"/>
</fieldset>
<fieldset class="pure-group">
<input id="email" name="email" type="hidden" value="test#gmail.com"/>
</fieldset>
<button class="button-success pure-button button-xlarge">
Upload</button>
<div style="display:none;" id="thankyou_message">
<div id="status" style="display: none">
<h2>Uploading. Please wait...</h2>
</div>
</div>
function picUploadJs(frmData) {
document.getElementById('status').style.display = 'inline';
google.script.run
.withSuccessHandler(updateOutput)
.processForm(frmData)
};
function updateOutput() {
var outputDiv = document.getElementById('status');
outputDiv.innerHTML = "<h2>File successfully uploaded!</h2><button class=\"pure-button\">Upload another</button>";
}
The original code comes from here
and here
I probably don't have all the lingo correct, but you have to turn the form submission fields into variables to be able to use them in your .gs script. Once you turn them into variables, you can "build" a filename to your liking, and use it when writing the fileBlob to a file. Given your code above, you should be able to just modify the processForm function as follows:
function processForm(theForm) {
var fileBlob = theForm.fileUpload;
var manufacturer = theForm.manufacturer;
var issueDate = theForm.issueDate;
var myNewFilename = manufacturer + '_' + issueDate + '.pdf';
fileBlob.setName(myNewFilename); //set Name of the blob
var fldrSssn = DriveApp.getFolderById('my Google Drive folder id');
fldrSssn.createFile(fileBlob); // create a file with the blob, name of the file will be the same as set by setName method
return true;
}
Let me also note something that may be helpful for future visitors--how to write a timestamp into the filename. Set a new variable using the Utilities.formatDate function, and then you can concatenate this variable into a filename like in the example above. Here's how to set the variable:
var myTS = Utilities.formatDate (new Date(), Session.getScriptTimeZone(), "yyyyMMdd_HHmmss--") ;
Format is completely flexible--just look up the function for details.
You may want to use the rename(newName) method which renames the document.
var ss = SpreadsheetApp.getActiveSpreadsheet();
ss.rename("This is the new name");
Also, here's a related threads: https://productforums.google.com/forum/#!topic/docs/AP9zMPOyjfg and Copy, rename and move a document which might help.

.remove(":contains()") not working

I have a input field where value is equal to the id's and a button. When that button is triggered I want to remove the id in the input field also the button where the value is equal to the data stored in the input field or the id. Here http://jsfiddle.net/leonardeveloper/hcfzL/3/
HTML:
<form id="materialForm" action="#" method="post">
<input id="materials" type="text" name="materials" value="1,2,3" readonly="readonly" disabled="disabled" />
</form>
<div id="display">
<button class="removes" value="1">x</button>
<button class="removes" value="2">x</button>
<button class="removes" value="3">x</button>
</div>
JS:
$(document).on('click', '.removes', function () {
var id = $(this).val();
alert(id);
$('#materials').remove(":contains('" + id + "')");
$('#display').remove(":contains('" + id + "')");
return false;
});
.remove() is for removing DOM elements, not text from values. And it removes the element it's applied to, not elements that are contained within it.
$(document).on('click', '.removes', function () {
var id = $(this).val();
alert(id);
var materials = $('#materials').val().split(',');
materials = materials.filter(function(e) {
return e != id;
});
$('#materials').val(materials.join(','));
$(this).remove();
return false;
});
FIDDLE
The :contains selector is for selecting DOM nodes that contain other DOM nodes. In your case you look to be selecting input elements which have a particular string in their value.
You should probably use .filter to filter to select the input elements that match the filter.
Try
$(document).on('click','.removes',function(){
var id = $(this).val();
$('#materials').val(function(){
var value = this.value, array = value.split(',');
var idx = $.inArray(id, array);
if(idx >=0 ){
array.splice(idx, 1)
value = array.join(',')
}
return value;
})
$(this).remove();
return false;
});
Demo: Fiddle

Incrementing value (integer) in an input type field

I have input text and I want to increase the number that is inside using the key up or down.
I have:
<input type="text" value="1" name="qty" />
After digging stackoverflow I found: Is it possible to handle up/down key in HTML input field?
The solution is to use: Keycodes 37 - 40 should do it for you. They map as 37=left, 38=up, 39=right, 40=down.
But How can I use these code in my form? Is there a Javascript function that do this (like : increase() or decrease()?
Thanks
You could do something like this, using the "onkeydown" event.
<script type="text/javascript">
function increment(e,field) {
var keynum
if(window.event) {// IE
keynum = e.keyCode
} else if(e.which) {// Netscape/Firefox/Opera
keynum = e.which
}
if (keynum == 38) {
field.value = parseInt(field.value)+ 1;
} else if (keynum == 40) {
field.value = parseInt(field.value) - 1;
}
return false;
}
</script>
<input type="text" onkeydown="increment(event, this)" value="10">

Removing form validation causes form not to submit?

I've removed pretty much all .js references in my Magento theme. Specifically I've removed the onclick from the add to cart button.
in template/catalog/product/view/addtocart.phtml I've removed onclick="productAddToCartForm.submit(this)
in template/catalog/product/view/view.phtml I removed this block of code...
<script type="text/javascript">
//<![CDATA[
var productAddToCartForm = new VarienForm('product_addtocart_form');
productAddToCartForm.submit = function(button, url) {
if (this.validator.validate()) {
var form = this.form;
var oldUrl = form.action;
if (url) {
form.action = url;
}
var e = null;
try {
this.form.submit();
} catch (e) {
}
this.form.action = oldUrl;
if (e) {
throw e;
}
if (button && button != 'undefined') {
button.disabled = true;
}
}
}.bind(productAddToCartForm);
productAddToCartForm.submitLight = function(button, url){
if(this.validator) {
var nv = Validation.methods;
delete Validation.methods['required-entry'];
delete Validation.methods['validate-one-required'];
delete Validation.methods['validate-one-required-by-name'];
if (this.validator.validate()) {
if (url) {
this.form.action = url;
}
this.form.submit();
}
Object.extend(Validation.methods, nv);
}
}.bind(productAddToCartForm);
//]]>
</script>
However, now when I submit the form I get nothing.
I figured to change the add to cart <button> to a proper submit. So I changed this....
<button type="button" title="<?php echo $buttonTitle ?>" class="button btn-cart"><span><span><?php echo $buttonTitle ?></span></span></button>
to this ...
<input type="submit" value="<?php echo $buttonTitle ?>" />
When I do that, the form submits but I get a "Page Not Found", the URL it takes me to looks like this /checkout/cart/add/uenc/aHR0cDovLzcwLjMyLjc0LjQ2L3J0bF9tYWdlbnRvL2luZGV4LnBocC9jYXRhbG9nL3Byb2R1Y3Qvdmlldy9pZC8xNQ,,/product/15/
Is it not possible to submit a form the old fashioned way in Magento without javascript? If it is, can you give some pointers?
My plan was to hook up my own jQuery validation (which is quite simple, I just need to validate that the qty field has length) and ditch some of the ridiculousness of the code above.
I don't know how and I don't know why, but when I disable "Use Web Server Rewrites" it works with the standard submit button.

Jquery retrieve values of Dynamically created elements

I have a html page with a form.
The form has Div which gets populated dynamically with Input elements like text box,radio,checkbox etc.
Now I want to retrieve the values of these dynamically created elements in the Html page,so that i can submit it to a page.
//HTML PAGE
<script type="text/javascript">
$(function() {
populateQuestions();
});
$("#submit_btn").click(function() {
// validate and process form here
//HOW TO ??retrieve values???
var optionSelected = $("input#OptionSelected_1").val();// doesn't work?
// alert(optionSelected);
postAnswer(qid,values);//submit values
showNextQuestion() ;// populate Div Questions again new values
});
</script>
<form action="" name="frmQuestion">
<div id="Questions" style="color: #FF0000">
</div>
//Question DIV generation script example radio buttons
//questionText text of question
//option for question questionOptions
// **sample call**
var question = createQuestionElement("1","MCQ", "WHAT IS ABCD??", "Opt1$Opt2$Opt3");
question.appendTo($('#Questions'));
function createQuestionElement(id, type, questionText, questionOptions) {
var questionDiv = $('<div>').attr('id', 'Question');
var divTitle = $('<div>').attr('id', 'Question Title').html(questionText);
divTitle.appendTo(questionDiv);
var divOptions = $('<div>').attr('id', 'Question Options');
createOptions(id, "radio", questionOptions, divOptions);
divOptions.appendTo(questionDiv);
return questionDiv;
}
function createOptions(id, type, options, div) {
var optionArray = options.split("$");
// Loop over each value in the array.
$.each(
optionArray, function(intIndex, objValue) {
if (intIndex == 0) {
div.append($("<input type='" + type + "' name='OptionSelected_" + id + "' checked='checked' value='" + objValue + "'>"));
} else {
div.append($("<input type='" + type + "' name='OptionSelected_" + id + "' value='" + objValue + "'>"));
}
div.append(objValue);
div.append("<br/>");
}
You are creating the same input multiple times, since you're splitting the option array, you're making this:
<input type='radio' name='OptionSelected_1' checked='checked' value='Opt1'>
<input type='radio' name='OptionSelected_1' value='Opt2'>
<input type='radio' name='OptionSelected_1' value='Opt3'>
You are currently fetching by ID with the #, instead you want to fetch by name and get the :checked item, like this:
var optionSelected = $("input[name=OptionSelected_1]:checked").val();