Created
May 15, 2017 20:20
-
-
Save GoodChancer/c359cce22790639c5010005f939163ee to your computer and use it in GitHub Desktop.
Saving URL parameters as cookies and adding to forms
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
This script will take the URL parameters of your choice and save them to cookies during a user session, | |
so if a user changes pages on your site, the data will still be submitted with your forms. | |
Be sure to include the JS Cookie plugin https://github.com/js-cookie/js-cookie and jquery. | |
Add the code below to your website footer. | |
Adjust variable, parameter, and form input names accordingly, add or remove as necessary. | |
Note: some servers block files with 'cookie' in the name. Be sure to change the filename if you have problems loading the script. | |
This code is based on Jenna Molby's tutorial: | |
http://jennamolby.com/how-to-use-cookies-to-capture-url-parameters/ | |
*/ | |
// 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('source'); | |
var medium = getParameterByName('medium'); | |
var campaign = getParameterByName('campaign'); | |
// Set the cookies | |
if(Cookies.get('source') == null || Cookies.get('source') == "") { | |
Cookies.set('source', source); | |
} | |
if(Cookies.get('medium') == null || Cookies.get('medium') == "") { | |
Cookies.set('medium', medium); | |
} | |
if(Cookies.get('campaign') == null || Cookies.get('campaign') == "") { | |
Cookies.set('campaign', campaign); | |
} | |
// Grab the cookie value and set the form field values | |
$(document).ready(function(){ | |
$('input[name=source').val(source); | |
$('input[name=medium').val(medium); | |
$('input[name=campaign').val(campaign); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment