I have been working on pre-filling a Cognito Form based on a customers answer to a different form on our website. I have gotten to the point where the JS variables contain the strings I would like to pre-fill into different fields, but I have tried everything from putting it into the Cognito.load() function, through inserting it as the value for an input field with .value() on a element ID.
I currently have two fields that pre-fill and work just fine by inserting JS variables through Cognito.load(), but the other fields will not.
<div class="cognito">
<script src="https://services.cognitoforms.com/s/0XJ-E4DafE--nZOqqp-Haw"></script>
<style>
[data-field="Source"], [data-field="Query"] {display:none;}
</style>
<script>
var url = window.location.hostname + window.location.pathname;
var query = window.location.search;
function getAllUrlParams(link) {
var queryString = link ? link.split('?')[1] : window.location.search.slice(1);
var obj = {};
if (queryString) {
queryString = queryString.split('#')[0];
var arr = queryString.split('&');
for (var i=0; i<arr.length; i++) {
var a = arr[i].split('=');
var paramNum = undefined;
var paramName = a[0].replace(/\[\d*\]/, function(v) {
paramNum = v.slice(1,-1);
return '';
});
var paramValue = typeof(a[1])==='undefined' ? true : a[1];
if (obj[paramName]) {
if (typeof obj[paramName] === 'string') {
obj[paramName] = [obj[paramName]];
}
if (typeof paramNum === 'undefined') {
obj[paramName].push(paramValue);
}
else {
obj[paramName][paramNum] = paramValue;
}
}
else {
obj[paramName] = paramValue;
}
}
}
return obj;
}
var nameFirst = decodeURIComponent(getAllUrlParams().nf);
var nameLast = decodeURIComponent(getAllUrlParams().nl);
var userEmail = decodeURIComponent(getAllUrlParams().e);
var userPhone = decodeURIComponent(getAllUrlParams().p);
Cognito.load("forms", { id: "44", entry: { "Source": url, "Query" : query, "Name": {"First": nameFirst, "Last": nameLast}, "Phone": userPhone, "PrimaryEmailAddress": userEmail}
});
As I mentioned above, the variables nameFirst, nameLast, userEmail, and userPhone all contain the proper information in them in my console. Insights would be appreciated!
Best Answer
Disclaimer: I'm an engineer on the Cognito Forms team!
I created a mock form and was unable to replicate the problem, however, a few things you might want to note:
Source
andQuery
field's visibility Internal, you can still pre-populate it, and it will not be visible to your end usersName
,Phone
, andPrimaryEmailAddress
) are within a section, you must specify the section name in the pre-fill. One way to determine the underlying structure of the form is to set up a test JSON webhook (as outlined in this article), create a sample entry, and take a look at the JSON output that is captured by requestb.in.If you would like specific assistance with your form, please contact us via the Support option in the top-level menu.