Trying to extract information from querystring - javascript

I'm new to JavaScript and I am trying to extract information from a query string on the web I created, if I load straight on the page without the query string the page will load but once I redirect from my form page to the page where I'm doing the parsing it freezes and crashes... can anyone help please! :(
http://main.xfiddle.com/7d679c3a/Project1/Commission.php
http://main.xfiddle.com/7d679c3a/Project1/contactForm.php
http://main.xfiddle.com/7d679c3a/Project1/DiceRoll.php
http://main.xfiddle.com/7d679c3a/Project1/IsEven.php
http://main.xfiddle.com/7d679c3a/Project1/palindrome.php
http://main.xfiddle.com/7d679c3a/Project1/part1.php
http://main.xfiddle.com/7d679c3a/Project1/passwordStrength.php
http://main.xfiddle.com/7d679c3a/Project1/allinOne.php
JavaScript Code
var $ = function(id)
{
return document.getElementById(id);
}
var formInfo = location.search();
formInfo = formInfo.substring(1, formInfo.length);
while (formInfo.indexOf("+") != -1)
{
formInfo = formInfo.replace("+", " ");
}
while (formInfo.indexOf("=") != -1)
{
formInfo.replace("=", " ");
}
formInfo = decodeURI(formInfo);
formInfo.replace("firstname", "");
formInfo.replace("lastname", "");
formInfo.replace("phonenumber", "");
formInfo.replace("postalcode", "");
formInfo.replace("startingmoney", "");
var infoArray = formInfo.split("&");
var firstName = infoArray[0];
var lastName = infoArray[1];
var phoneNumber = infoArray[2];
var postalCode = infoArray[3];
var startingMoney = infoArray[4];
$("playername").innerHTML = firstName + " " +lastName;
$("playerinfo").innerHTML = phoneNumber + " " + postalCode;
$("money").innerHTML = " $$" + startingMoney;
HTML Code
<div id="fireinfo">
<p id="playername"></p><br/>
<p id="playerinfo"></p>
<p id="money"></p>
</div>
I want to out put the information i get from the query string into the player name, player info and money id's.

Use this function to get query string value:
function getQueryString(name) {
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(window.location.search);
return results == null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
};
var firstname = getQueryString('firstname');

Related

How do I fix the error illegal return statement on line 62 in apps script?

I am creating a app in mit app inventor and the functionality of the app is to read and send data to google sheet. For that I have written a code in apps script but it shows that there is a illegal return statement on line 62 which has been highlighted-( if(getPWD==password){return ContentService.createTextOutput(getFullName);} ). Please help on how to fix this.
Code:-
//**************************************************************************************
function doGet(e){
return Authentication(e);
}
function doPost(e){
return Authentication(e);
}
function Authentication(e){
if(e.parameter.func == "Create") {
var ss = SpreadsheetApp.openById(e.parameter.ID);
var sh = ss.getSheetByName(e.parameter.SH);
var rg = sh.getName() + "!" + sh.getDataRange().getA1Notation();
var email = e.parameter.email;
var sql = ' "Select B where B=\''+email+'\' " ';
var qry = ' =IFERROR(query(' + rg + ',' + sql + '), "")';
var ts = ss.insertSheet();
var setQuery = ts.getRange(1,1).setFormula(qry);
var getResult = ts.getDataRange().getValues();
ss.deleteSheet(ts);
if (getResult ==""){
var data = [e.parameter.fullname, e.parameter.email, e.parameter.password, e.parameter.phone];
sh.appendRow(data);
return ContentService.createTextOutput(getResult);}
}
}
// ********************************************************************************************************
if(e.parameter.func == "Login") {
var ss = SpreadsheetApp.openById(e.parameter.ID);
var sh = ss.getSheetByName(e.parameter.SH);
var email = e.parameter.email;
var password = e.parameter.password;
var rg = sh.getName() + "!" + sh.getDataRange().getA1Notation();
var sql = ' "Select A,B,C where B=\''+email+'\' " ';
var qry = ' =IFERROR(query(' + rg + ',' + sql + '), "")';
var ts = ss.insertSheet();
var setQuery = ts.getRange(1,1).setFormula(qry);
var getResult = ts.getDataRange().getValues();
var getPWD = ts.getRange(1,3).getValues();
var getFullName = ts.getRange(1,1).getValues();
ss.deleteSheet();
if(getResult!=""){
if(getPWD==password){return ContentService.createTextOutput(getFullName);}
else{ return ContentService.createTextOutput("ERPWD");}
}
else{return ContentService.createTextOutput(getResult);}
}

Displaying Associative array values using HTML elements

I want to display the value of an associative array using html elements, but I can't seem to get the values because it always outputs undefine.
my code works like this : the user will register data, the registered data will be stored in an object and will be using a key "username" to access it. When a user search a username the values must be displayed using html elements.
here is my code. thank you
var storage = [];
function viewUserArray()
{
var zName = document.getElementById('checkArray').value;
var html = "<h1> Username Details </h1>";
var anotherhtml = "<p>";
var uName;
var fName;
var elmail;
var pword;
var b_day;
var g_nder;
for (key in storage)
{
if(key === zName)
{
uName = storage[key].uName;
fName = storage[key].fName;
elmail = storage[key].elmail;
pword = storage[key].pword;
b_day = storage[key].b_day;
g_nder = storage[key].g_nder;
html += "<p>Username : " + uName + "</p>";
html += "<p>Full Name : " + fName + "</p>";
html += "<p>Email : " + elmail + "</p>";
html += "<p>Password : " + pword + "</p>";
html += "<p>Age : " + b_day + "</p>";
html += "<p>Gender : " + g_nder + "</p>";
}
document.getElementById("target").innerHTML = html;
}
}
function setValuesArray()
{
var uName = document.getElementById('username').value;
var fName = document.getElementById('fullName').value;
var elmail = document.getElementById('email').value;
var pword = document.getElementById('password').value;
var b_day = getAge();
var g_nder = document.getElementById('gender').value;
storage[uName] = (storage[uName]||[]).concat({//add user to storage[uName]
"Username" : uName,
"Full Name" : fName,
"Email" : elmail,
"Password" : pword,
"Age" : b_day,
"Gender" : g_nder
});
}
Pretty much same as other answer:
var storage = {};
function viewUserArray()
{
var zName = document.getElementById('checkArray').value;
var html = "<h1> Username Details </h1>";
var anotherhtml = "<p>";
var uName;
var fName;
var elmail;
var pword;
var b_day;
var g_nder;
if(!storage[zName]){
console.log("doesn't exist");
return;
}
uName = storage[zName].uName;
fName = storage[zName].fName;
elmail = storage[zName].elmail;
pword = storage[zName].pword;
b_day = storage[zName].b_day;
g_nder = storage[zName].g_nder;
html += "<p>Username : " + uName + "</p>";
html += "<p>Full Name : " + fName + "</p>";
html += "<p>Email : " + elmail + "</p>";
html += "<p>Password : " + pword + "</p>";
html += "<p>Age : " + b_day + "</p>";
html += "<p>Gender : " + g_nder + "</p>";
document.getElementById("target").innerHTML = html;
}
}
function setValuesArray()
{
var uName = document.getElementById('username').value;
var fName = document.getElementById('fullName').value;
var elmail = document.getElementById('email').value;
var pword = document.getElementById('password').value;
var b_day = getAge();
var g_nder = document.getElementById('gender').value;
//I assume there is only one uName so update the uName if it exist and create it if it doesn't
// storage[uName] = (storage[uName]||[]).concat({//add user to storage[uName]
storage[uName] = {//update or add
uName,
fName,
elmail,
pword,
b_day,
g_nder
};
}
You also don't consistently get the values under the same keys that you save them in:
You save a user as: "Username" : uName, but then magically expect to get the value with: storage[zName].uName Saving a value under key "Username" but then try to get the value using a key "uName"

adding style to items in an array

I am doing a madlibs-type program. Prompts ask for words, which are then added to a string. I would like the words used from the prompts to be underlined when they are displayed with the rest of the string. I have created an array with all the prompts. Now, I just need to know how to run through that array and change the text-decoration to "underline". I know I need to use a for-loop through the array, but not sure of how to approach it.
What is the best way to make this happen?
HTML:
<body>
<div id = "story-space">
</div>
<script src = "madlibs.js"></script>
</body>
JS:
var prompt1 = prompt("Enter a animal.");
var prompt2 = prompt("Enter a city.");
var prompt3 = prompt("Enter an activity.");
var prompts = [prompt1, prompt2, prompt3, prompt4];
var text = "There was once was a " + prompt1 + " from " + prompt2 + " who liked to " + prompt3 + "."
document.getElementById("story-space").innerHTML = text;
Why can you add the html style like this
var text = "There was once was a <span style='text-decoration:underline'>" + prompt1 + "</span> from <span style='text-decoration:underline'>" + prompt2 + "</span> who liked to <span style='text-decoration:underline'>" + prompt3 + "</span>."
one simple way you can do it it as follows, note that you need to check for empty strings returned from prompt though, which is not handled in this answer,
var questions = ['an animal', 'a city', 'an activity'],
answers = [];
// create source string with placeholders that
// can be replaced with values in from prompts
var sourceText = "There was once was a {0} from {1} who liked to {2}."
//loop thru questions array and store answers in 'answers' variable
for (var q = 0; q < questions.length; q++) {
//create answer as span element
var question = questions[q],
answer = '<span style="text-decoration:underline;">';
answer += prompt('Enter ' + question);
answer +='</span>';
//update source text's 'qth' placeholder with answer
sourceText = sourceText.replace( new RegExp( "\\{" + q + "\\}", "g" ), function() {
return answer;
});
}
//update the target element's innerHTML
document.getElementById("story-space").innerHTML = sourceText;
You can try something like this by mapping all the prompts with an underline class.
var prompt1 = prompt("Enter a animal.");
var prompt2 = prompt("Enter a city.");
var prompt3 = prompt("Enter an activity.");
var prompts = [prompt1, prompt2, prompt3];
prompts = prompts.map(prompt => `<span class="underline">${prompt}</span>`)
var text = "There was once was a " + prompts[0] + " from " + prompts[1] + " who liked to " + prompts[1] + "."
document.getElementById("story-space").innerHTML = text;
.underline {
text-decoration: underline;
}
<div id = "story-space">
</div>
You can also try something like below where you just provide the pre-text for your prompt and let the Map and Reduce do the rest of the job for you.
let textPromptMap = new Map();
textPromptMap.set("There was once was a ", prompt("Enter a animal."))
textPromptMap.set(" from ", prompt("Enter a city."))
textPromptMap.set(" who liked to ", prompt("Enter an activity."))
const text = [...textPromptMap.keys()]
.reduce((a, b) =>
`${a}${b}<span class="underline">${textPromptMap.get(b)}</span>`, ""
)
document.getElementById("story-space").innerHTML = text;
.underline {
text-decoration: underline;
}
<div id = "story-space">
</div>

Javascript function to strip user ID from URL

i need a javascript function to strip the user ID from a given URL.
for example. i have this URL http://www.example.com/member.php?id=100001877097904
how can i retrieve the ID of the user from that URL?
Thanks in advance.
function getParameterByName(url, name)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(url);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
One possible solution:
var url = "http://www.example.com/member.php?id=100001877097904",
id = (url.match(/[?&#]id=(\d+)/) || []).pop();
console.log(id);

Get auth token from URL

I am trying to get a Twitter oauth token using the below string. How can I "run" the string and then get the token?
This is the request string:
https://api.twitter.com/oauth/request_token?oauth_consumer_key=9TL0JGKTIv7GyOBeg8ynuxg&oauth_nonce=Xty48&oauth_signature=3skps99e6zkn0rcUGadVUEuHFon4%3D&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1346603336
This is the result:
oauth_token=TBFdNoytaizrfMAWNZ6feqNz3BsozHk5AesIioX8u8Ec&oauth_token_secret=DtQ3jiUIeVdRcBAKwVQJRWpgKtEHi3m1ylk0nlsHCBj0&oauth_callback_confirmed=true
See answer to this question. It demonstrates how to get a value from the querystring.
Here, I've altered it to take the name value collection as a parameter:
function getParameterByName(name, qs)
{
name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
var regexS = "[\\?&]" + name + "=([^&#]*)";
var regex = new RegExp(regexS);
var results = regex.exec(qs);
if(results == null)
return "";
else
return decodeURIComponent(results[1].replace(/\+/g, " "));
}
Usage:
var result = "oauth_token=TBF...&oauth_token_secret=DtQ...";
var token = getParameterByName("oauth_token", result);

Categories

Resources