JS Function URL Parameters - Null Value [duplicate] - javascript

This question already has answers here:
Get the values from the "GET" parameters (JavaScript) [duplicate]
(63 answers)
Closed 2 years ago.
I am trying to pull URL parameters to pass to a prebuilt HTML form.
The example URL is:
?state=CA&**period**=PERIOD_FIXED_30YEARS&**loan**=200000&ltv=80&**transaction**=54&property_type=34&fico=740&occupancy=49&cashout=0&rate=4.125&fees=510&points=0.204&trackingID=1445830871741638005
The text in bold is what I would need to pull.
I was trying to do this through:
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, " "));
}
//Gathering the URL Parameters
var period = getParameterByName('period');
var loan = getParameterByName('loan');
var ltv = getParameterByName('ltv');
var transaction = getParameterByName('transaction');
var property_type = getParameterByName('property_type');
var fico = getParameterByName('fico');
var occupancy = getParameterByName('occupancy');
var cashout = getParameterByName('cashout');
var rate = getParameterByName('rate');
var fees = getParameterByName('fees');
var points = getParameterByName('points');
var trackingID = getParameterByName('trackingID');
And then assign to the form using
document.getElementById("tfa_49").value = period;
document.getElementById("tfa_50").value = loan;
I keep getting a null error and I think it is the regex.
Any help would be appreciated. I searched similar questions on the site and none of the answers worked in my situation.
UPDATING WITH WORKING CODE:
<script type="text/javascript">
//Used to pull URL
const link = window.location.href;
const url = new URL(link);
//Function to get the URL parameters
function getParameterByName(name) {
return url.searchParams.get(name);
}
//Gathering the URL Parameters and writing to console to check if parse is accurate -- Note the console.log can be removed if needed
var period = getParameterByName('period');
console.log(period);
var loan = getParameterByName('loan');
console.log(loan);
var ltv = getParameterByName('ltv');
console.log(ltv);
var transaction = getParameterByName('transaction');
console.log(transaction);
var property_type = getParameterByName('property_type');
console.log(property_type);
var fico = getParameterByName('fico');
console.log(fico);
var occupancy = getParameterByName('occupancy');
console.log(occupancy);
var cashout = getParameterByName('cashout');
console.log(cashout);
var rate = getParameterByName('rate');
console.log(rate);
var fees = getParameterByName('fees');
console.log(fees);
var points = getParameterByName('points');
console.log(points);
var trackingID = getParameterByName('trackingID');
console.log(trackingID);
//On load function to prefill the forms hidden fields
$( document ).ready(function() {
document.getElementById("tfa_49").value = period;
document.getElementById("tfa_50").value = loan;
document.getElementById("tfa_51").value = ltv;
document.getElementById("tfa_53").value = transaction;
document.getElementById("tfa_54").value = property_type;
document.getElementById("tfa_55").value = fico;
document.getElementById("tfa_56").value = occupancy;
document.getElementById("tfa_57").value = cashout;
document.getElementById("tfa_58").value = rate;
document.getElementById("tfa_59").value = fees;
document.getElementById("tfa_60").value = points;
document.getElementById("tfa_61").value = trackingID;
});
</script>

You can create an URL object and then use the url.searchParams.get(param) method to get the desired parameter. More information.
Working example:
const link = "http://www.example.com/test.html?state=CA&period=PERIOD_FIXED_30YEARS&loan=200000&ltv=80&transaction=54&property_type=34&fico=740&occupancy=49&cashout=0&rate=4.125&fees=510&points=0.204&trackingID=1445830871741638005";
const url = new URL(link);
function getParameterByName(name) {
return url.searchParams.get(name);
}
//Gathering the URL Parameters
var period = getParameterByName('period');
console.log(period);
The hardcoded url is just for the example with your URL, in your code use:
const url = window.location.href

Related

Google Form creates Google Slides from template Script

I have a script that on Form submit takes the data from the spreadsheet and creates a copy of a template and populates the google docs. I am trying to accomplish the same thing from google form to google slides.
First script I use for the google forms to google docs. The second script is my attempt of using the same principles and applying to google slides. My issue is I'm getting an error saying TypeError: values.forEach is not a function (line 109, file "Code") in relation to values.forEach(function(page). Any suggestions on how I could go about solving this?
Google Form to Google Sheets
function autoFillGoogleDocFromForm(e) {
var timestamp = e.values[0];
var address = e.values[1];
var image = e.values[2];
var price = e.values[3];
var summary = e.values[4];
var type = e.values[5];
var year_built = e.values[6];
var bed = e.values[7];
var bath = e.values[8];
var home_size = e.values[9];
var lot_size = e.values[10];
var occupancy = e.values[11];
var templateFile = DriveApp.getFileById("xxxxxxxx");
var templateResponseFolder = DriveApp.getFolderById("yyyyyyyyyy")
var copy = templateFile.makeCopy( address , templateResponseFolder);
var doc = DocumentApp.openById(copy.getId())
var body = doc.getBody();
body.replaceText("{{address}}", address);
body.replaceText("{{price}}", price);
body.replaceText("{{summary}}", summary);
body.replaceText("{{type}}", type);
body.replaceText("{{year_built}}", year_built);
body.replaceText("{{beds}}", bed);
body.replaceText("{{baths}}", bath);
body.replaceText("{{home_size}}", home_size);
body.replaceText("{{lot_size}}", lot_size);
body.replaceText("{{occupancy}}", occupancy);
doc.saveAndClose;
}
Google Form to Google Slides
function generateLandingPagesReport(){
var dataSpreadsheetUrl = "https://docs.google.com/spreadsheets/xxxxxxxxx/edit"
var Presentation_ID = "xxxxxxxxxxxxxx";
var ss = SpreadsheetApp.openByUrl(dataSpreadsheetUrl);
var deck = SlidesApp.openById(Presentation_ID);
var sheet = ss.getSheetByName('Sheet1');
var values = sheet.getRange('A1:J17').getValues;
var slides = deck.getSlides();
var templateSlide = slides[1];
var presLength = slides.length;
values.forEach(function(page){
values.forEach(function(page){
if(page[0]){
var landingPage = page[0];
var sessions = page[1];
var newSessions = page[2];
}
templateSlide.duplicate(); // duplicate the template page
/*slides = deck.getSlides(); // update the slides array for indexes and length*/
newSlide = slides[2]; // declare the new page to update
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}', landingPage);
shape.getText().replaceAllText('{{sessions}}', sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
});
presLength = slides.length;
newSlide.move(presLength);
//end our condition statement
}); //close our loop of values
//remove template slide
templateSlide.remove();
});
}
You're missing the parenthesis when calling the getValue() method.
Change this:
var values = sheet.getRange('A1:J17').getValues;
To this:
var values = sheet.getRange('A1:J17').getValues();
Not exactly what I was looking for but this uses the first Row to identify the tag inside the Google slides template like {{title}} and replaces that with the value in the second row of the sheet
function createPresentation() {
var templateFile = DriveApp.getFileById("1YVEA4WtU1Kf6nZRgHpwnKBIR-V6rRN6s9zCdOQDkWNI");
var templateResponseFolder = DriveApp.getFolderById("1k7rcfXODij4o4arSULuKZUHbit1m_X64");
var copy = templateFile.makeCopy("New" , templateResponseFolder);
var Presentation = SlidesApp.openById(copy.getId());
var values = SpreadsheetApp.getActive().getDataRange().getValues();
values.forEach(function(row) {
var templateVariable = row[0];
var templateValue = row[1];
Presentation.replaceAllText(templateVariable, templateValue);
});
}
After you have copy the template page, you work on it and try to do replace.
However, change may be pending such that newSlide = slides[2]; give undefined.
You may need to try saveAndClose() before performing any actions.
templateSlide.duplicate(); // duplicate the template page
/*slides = deck.getSlides(); // update the slides array for indexes and length*/
/* flush the presentation */
deck.saveAndClose();
deck = SlidesApp.openById(Presentation_ID);
slides = deck.getSlides();
newSlide = slides[2]; // declare the new page to update
var shapes = (newSlide.getShapes());
shapes.forEach(function(shape){
shape.getText().replaceAllText('{{landing page}}', landingPage);
shape.getText().replaceAllText('{{sessions}}', sessions);
shape.getText().replaceAllText('{{new sessions}}',newSessions);
});

TypeError: Cannot read property "values" from undefined. onEdit # ClosedTSR.gs:3

// When Form Gets edited
function onEdit(e) {
var Timestamp = e.values[2];
var email_sender = e.values[3];
var email_address = "";
var TSRNumber = e.values[19];
var IssueType = e.values[4];
var Region = e.values[0];
var Customer = e.values[5];
var ShortName = e.values[6];
var City = e.values[9];
var State = e.values[10];
var Contact = e.values[11];
var Product = e.values[12];
var TankCode = e.values[13];
var ProbDesc = e.values[14];
var Terminal = e.values[1];
var Priority = e.values[18];
var TSRStatus = e.values[22];
// Check if TSR is Closed
if(TSRStatus == "Closed"){
switch (Region) {
case "East":
email_address = xxxxxxxx
Basically when a user changes a cell value to "Closed" I am trying to send an email containing information from that specific row.
There is no values array in an onEdit trigger event object. There is for an onFormSubmit trigger.
event objects
I recommend reading before coding or at least during coding

How to pass a string value to firebase child( )?

It works like this:
var firebaseRef = firebase.database().ref().child(document.getElementById("areaCode").value);
Or any suggestions to pass x like this:
var areaCodex = document.getElementById("areaCode");
var x = areaCodex.toString();
firebase.initializeApp(config);
var rootRef = firebase.database().ref().child(x);
$('#saveBtn').click(function() {
rootRef.set({
date: $('#date').val(),
timeF: $('#fromTime').val()
});
})
I need to save data to Firebase and my code is as follows:
var toTime = document.getElementById("toTime");
var areaCode = document.getElementById("areaCode");
function submitClick(){
var firebaseRef = firebase.database().ref().child();//here in .child() i need to pass the areaCode as an argument. It works when i hardcode a value like .child('1234'). But i need that to be what ever the value I am getting from the textbox of areaCode. I have tried //var x = areaCode.value; // var y = x.toString and var y = String(x); , trying to pass y as .child(y)
// also var y = areaCode.toString(); does not work.
var toTimeText = toTime.value;
firebaseRef.child("toTime").set(toTimeText);
window.confirm("Data has been successfully sent.");
}
Any help highly appreciated.
try this
function sumbitClick(){
var toTimeText = document.getElementById("toTime").value;
var ref = firebase.database().ref(path_to_your_child);
ref.once("value")
.then(function(snapshot) {
ref.set(toTimeText);
});
}

Declaring JavaScript variables in a HTML link

Say I have a simple HTML document with the following:
cake
pie
and results.html contains a variable that needs to be declared in Javscript as 100 for the first link, 200 for the second, and so on.
Is there any way I can make it so that when you click on the first link, it opens results.html with a javascript variable set to cake, the second one opens results.html with the variable set to pie, and so on?
You can pass them in the query string. For example:
cake
pie
In your results.html page you get and parse the query string. For example:
var queryStr = window.location.search.substring(1);
var params = parseQueryStr(queryStr);
console.log(params["result"]);
var parseQueryStr = function(queryStr) {
var params = {};
var queryArray = queryStr.split("&");
for (var i = 0, var l = queryArray.length; i < l; i++ ) {
var temp = queryArray[i].split('=');
params[temp[0]] = temp[1];
}
return params;
};
cake
pie
In results.html :
<script type="text/javascript">
function getQueryParams(qs) {
qs = qs.split("+").join(" ");
var params = {}, tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])]
= decodeURIComponent(tokens[2]);
}
return params;
}
var query = getQueryParams(document.location.search);
alert(query.keyword);
</script>

How to get the parameter value from URL in Jquery?

Hi all i have an url where i need to get an parameter from the url
var URL="http://localhost:17775/Students/199/Kishore"
//here from the url i need to get the value 199
this is what i had been trying but the value is null here
function getURLParameter(name) {
return parent.decodeURI((parent.RegExp(name + /([^\/]+)(?=\.\w+$)/).exec(parent.location.href) || [, null])[1]);
};
$(document).ready(function() {
getURLParameter("Students");
//i need to get the value 199 from the url
});
jQuery is not needed for this, though it could be used. There are lots of ways to skin this cat. Something like this should get you started in the right direction:
var URL="http://localhost:17775/Students/199/Kishore";
var splitURL = URL.split("/");
var studentValue = "";
for(var i = 0; i < splitURL.length; i++) {
if(splitURL[i] == "Students") {
studentValue = splitURL[i + 1];
break;
}
}
Here's a working fiddle.
Edit
Based on the comments, indicating that the position will always be the same, the extraction is as simple as:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.split("/")[4];
This is what you're looking for since the URL parameter will keep changing:
http://jsbin.com/iliyut/2/
var URL="http://localhost:17775/Students/199/Kishore"
var number = getNumber('Students'); //199
var URL="http://localhost:17775/Teachers/234/Kumar"
var number = getNumber('Teachers'); //234
function getNumber(section) {
var re = new RegExp(section + "\/(.*)\/","gi");
var match = re.exec(URL);
return match[1];
}
I would do the following:
var url = "http://localhost:17775/Students/199/Kishore";
var studentValue = url.match('/Students/(\\d+)/')[1]; //199

Categories

Resources