How do I access the querystring using javascript? - javascript

I have a querystring which looks like this page3.html?redesigndata=value which it appears if its redirected from page1.html and page3.html?new=yes or no when redirected from page2.html. Here is the code I'm using to find out what the querystring is and do some functions on page3.html
var locurl = window.location.search;
if (locurl.substring(0, 13) === '?redesigndata') {
alert("redesign!");
} else if (locurl.substring(0, 4) === '?new') {
visit = locurl.substring(5);
alert("somthing!");
if (visit === 'yes') {
alert("first!");
} else if (visit === 'no') {
alert("again!");
}
}
but I don't get any alerts when I try this script and I cant find out what's wrong with it.

Try using this function
function getQueryString() {
var result = {}, queryString = location.search.substring(1),
re = /([^&=]+)=([^&]*)/g, m;
while (m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
}
// ...
var myParam = getQueryString()["myParam"];
Check like this
if(getQueryString()["redesigndata"] != "")

There is nothing wrong with the code you posted. If the alerts never fire, it's because the conditions are never met. Once a query string is added to the URL that DOES match one of those you listed in your code, the alert does fire.
Also, beware you're (seemingly) creating global vars.

The script works on my box. Please put this script inside script tags

Related

Page reloads before reaching else statement in javascript

The problem in the code below resides in the if...else statement. If a user tries to create an account with a username or email already present in localStorage the program displays an error message. This works fine however if the if statement is false the page reloads before reaching the else statement. I have used console.log to check whether the else statement is run however as stated above the page reloads before ever reaching the else statement. I have also tried putting event.preventDefault in the if statement however that doesnt work either. Any help would be greatly appreciated. Thanks in advance.
Edit: the function is called using onclick in html when the button is pressed.
function storeRegistrationInfo(){
let person = {};
person.fullname = document.getElementById("regFullName").value;
person.username = document.getElementById("regUserName").value;
let username = document.getElementById("regUserName").value;
person.email = document.getElementById("regEmail").value;
person.password = document.getElementById("regPassword").value;
person.repeatedPassword = document.getElementById("repeatPassword").value;
let per = JSON.parse(localStorage.getItem(username));
if (person.username === per.username || person.email === per.email){
document.getElementById("signUpStatus").innerText = "Username or Email already taken!";
}else {
localStorage[person.username] = JSON.stringify(person);
}
event.preventDefault();
}
Andre, you are not receiving the event object.
Assume you are triggering this as part of onClick() ?
Try adding :
function storeRegistrationInfo(event)
Maybe need to add:
if( !(person === undefined) &&(person.username === per.username || person.email === per.email))

If else does not works properly

I have a Function (with help of other user of stackoverflow), but only the first if statement works, the second not. I want to take advantage of this code to get both: http and https followed or not by www
function formatURL() {
var url = document.getElementsByName("URL")[0];
var formattedURL = document.getElementsByName("formattedURL")[0];
url = url.value;
if (url.substr(0, 0) === "") // with our without www
{
formattedURL.value = "https://" + url;
return;
} else
{
formattedURL.value = "http://" + url;
return;
}
}
formattedURL.value = url;
}
You're running into this issue because url.substr(0,0) will always be an empty string "" for any string value of url (your if statement is always true).
Not sure what exactly you're trying to compare url.substr against because we don't have all the possible inputs you give to your <URL/> elements. Otherwise, I could have an actual fix for you.

Jquery domain validation after adding http

I need to do a URL validation for a CS form. I already have a script there that that checks for http and adds it if not there. However, if I add another function to do just validation, no matter where I put it, it returns URL invalid.
This is what I am running
<script type="text/javascript">
$(function(){
$('.url').blur(function(e) {
if ($(this).val().match(/^http/) || $(this).val().match(/^https/)) /*define the http & https strings */ {
$.noop() /*if strings exist, do nothing */
}
else {
// get value from field
var cur_val = $(this).val();
// do with cur_val
$(this).val('http://' + cur_val);
}
});
});
</script>
This is the second function I used for validation:
<script type="text/javascript">
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (pattern.test(url)) {
alert("Url is valid");
return true;
}
alert("Url is not valid!");
return false;
}
</script>
What am I doing wrong? I've tried to merge the 2 functions but my js skills choose that exact moment to fail.
Thank you!
I don't know, if this is what you are exactly looking for,
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
pattern.test("http://google.com"); // True
pattern.test("google.com"); // False
The if condition you are using is useless, since you return the result of the pattern match anyway.
So the updated Validate function should simply return the pattern results & should look like:
function validate() {
var url = document.getElementById("url").value;
var pattern = /(ftp|http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
return pattern.test(url);
}
Assuming that there is a DOM element with id url.
Just from an immediate look, it looks like your "add http" function is looking for tags with class="url", while the validate function is looking for tags with id="url". If you have nothing with that id, then I suppose it would always return invalid.

what is wrong with this JS cookie Script?

I have a code that has no syntax errors (Dreamweaver) but the Chrome JS console is saying that ExistsCookie is undefined. The cookie was in the cookie list for that site but the page is not redirecting. What am I doing wrong? NOTE: I know people can turn cookies off.
var cname = "voicevote"
var data ="1";
function CheckForCookie()
{
if( ExistsCookie(cname) )
{
window.location.replace("cookie.htm")
}
}
Most likely, ExistsCookie is a function that you haven't included in your script- if this was taken from a tutorial on some other website, look there- there may be a function on that page which you forgot to include in your code.
EDIT: After some googling, it looks like this is what you need:
function ExistsCookie(name)
{
var aCookie = document.cookie.split("; ");
for (var i=0; i < aCookie.length; i++)
{
var aCrumb = aCookie[i].split("=");
if (name == aCrumb[0])
return true;
}
return false;
}
(Source, which appears to match original question)

Posting data into JavaScript from an URL

I have a javascript on my server, and i need to set a value / calling a function inside the javascript when calling a URL. Is there anyway of doing that ?
UPDATE:
<script type="application/x-javascript" src="test-test.js"></script>
Thats how it its loaded on the HTML site. And I want to call the function test(e,e) inside test-test.js, by putting in the URL in a browser with some values for e,e..
Unless you are using one of the few web servers that employs server-side JavaScript, your script is going to run in the browser after the page is loaded. If you want to include information from the URL in your script (and this assumes that you can use a query string without changing the server's behavior), you can use window.location.search to get everything from the question mark onwards.
This function will return either the entire query string (without the question mark) or a semicolon-delimited list of values matching the name value you feed it:
function getUrlQueryString(param) {
var outObj = {};
var qs = window.location.search;
if (qs != "") {
qs = decodeURIComponent(qs.replace(/\?/, ""));
var paramsArray = qs.split("&");
var length = paramsArray.length;
for (var i=0; i<length; ++i) {
var nameValArray = paramsArray[i].split("=");
nameValArray[0] = nameValArray[0].toLowerCase();
if (outObj[nameValArray[0]]) {
outObj[nameValArray[0]] = outObj[nameValArray[0]] + ";" + nameValArray[1];
}
else {
if (nameValArray.length > 1) {
outObj[nameValArray[0]] = nameValArray[1];
}
else {
outObj[nameValArray[0]] = true;
}
}
}
}
var retVal = param ? outObj[param.toLowerCase()] : qs;
return retVal ? retVal : ""
}
So if the URL was, say:
http://www.yoursite.com/somepage.html?name=John%20Doe&occupation=layabout
if you call getUrlQueryString() you would get back name=John Doe&occupation=layabout. If you call getUrlQueryString("name"), you would get back John Doe.
(And yes, I like banner-style indents. So sue me.)
You can use address plugin to be able to pass some condition in urls trough # symbol: http://my_site/my_page#your_condition
in the html you can write something like this:
<script>
$(function(){
// Init and change handlers
$.address.init().change(function(event) {
if (event.value == "your_condition")
run_my_finction();
});
)};
<script>
See this exaple for the futher help.
If you want to execute JavaScript from the browsers' address bar, you can use a self-invoking function:
javascript:(function () {
alert('Hello World');
/* Call the JavaScript functions you require */
})();

Categories