window.location.href not setting query parameters - javascript

I'm trying to set a new url, I've used:
window.location.href = <url>;
window.location.assign(<url>);
if the url contains a section with query string parameters, Eg. info?value=1
in IE the url will not show these parameters. I tried the above two in Chrome and Chrome does show the query parameters. What's the hack to get it to work in IE?

location.assign(encodeURIComponent('/step2.php?id=1'));
The problem is likely due to the value of your variables. If they contain special or invalid characters, those needs to be passed through encodeURIComponent before being assigned location.assign

Related

Stuck in a conditional redirect loop

I want the application to change the url in the browser to set the parameters if the parameters do not match the item value on initial load of the page.
I tried to create a conditional check to see if the substring matched anywhere within the URL. However, I get caught in a loop. Something tells me my use of wildcards is incorrect.
htp.p('<script>
if(window.location.href !== "*'||:P4_TEAM||'*") {
window.location.href = "https://apextserverurl/ords/f?p=80001:4:::::P4_TEAM:'||:P4_TEAM||'"
}
</script>');
Since the page item cannot be null, the thought is on the initial load, it will push the parameters into the URL and adjust accordingly. The actual result shows the url parameters load into the browser correctly, but it seems to fail the logic test on the javascript and keeps refreshing instead
Your page refreshes endlessly, because your if condition will always be true (Because you can't use wildcards in JavaScript...at least not like that) and window.location.href will reload your page.
You could use a Regex, but for your example a simple string.includes() is sufficient.
You can just check with includes() like so:
// If ':P4_TEAM' is not in the url
if(!window.location.href.includes(':P4_TEAM')) {
// Set the url to the provided string (and refresh the page)
window.location.href = "https://apextserverurl/ords/f?p=80001:4:::::P4_TEAM:'||:P4_TEAM||'";
}

passing veriable in url weird behaviour

I'm trying to pass a variable throught URL and it's doing something really weird in Chrome and Firefox, it seems is doing the same in OS.
The issue is that I'm trying to send a few variable in the URL this way:
document.location.href = 'http://www.ihaves.org/main.php?id='+facebookUser+'&first_name='+facebookName+'&last_name='+facebookName+'&locat='+locat_+'&locationlat='+facebookLat+'&locationlon='+facebookLon+'&mode=facebook';
The weird result is this:
http://www.ihaves.org/Vejer%20de%20la%20Frontera,%20Spain
when the expected result should be this one: (taken from IE)
http://www.ihaveseen.org/main.php?id=1215834998&first_name=Juanma%20De%20Los%20Santos&last_name=Juanma%20De%20Los%20Santos&locat=Vejer%20de%20la%20Frontera%20Spain&locationlat=36.25&locationlon=-5.96667&mode=facebook
I have detected that the problem is the variable called "locat", if I take it out then everything seems to go fantastic so I have thought that the comma of "Vejer de la Frontera, Spain" might be the problem so I have used:
var location_name = locationName.replace(/,/g, '');
But it keeps doing the same weird thing than before. Any idea? Does chrome accept an espace beetwen words? Remember firefox does exactly the same. By the way, I'm using GET_ in the PHP.
You should use encodeURI() on the Parameters when constructing the URL.
document.location.href = 'http://www.ihaves.org/main.php?id=' + encodeURIComponent(facebookUser);
Use:
encodeURIComponent(facebookName)
encodeURIComponent
You should be using encoded key/value pairs. Some characters will result in an invalid URL. For example:
mysite.com?name=Bed&Breakfast
will result in two values "name=Bed" and "Breakfast=" which is not what you would expect or want. Encoding would result in your URL:
mysite.com?name=Bed%26Breakfast
It may look funny but the URL is now valid and works as expected.

Data passed to other pages via hyperlink is being cut off

I have a form that contains 2 <select>, the first select auto-populates itself upon page load, while the second select populates itself based on the choice selected in the first select.
To accomplish this, whenever the the select's state changes, the selected value in the first would be passed to a seperate page where it is used to populate the 2nd <select>
Problem
The selected value( Food & Beverages in this case) which is passed through the url is being cut off halfway, causing an incomplete string to be send to the processing page for the 2nd , which causes it to be unable to run.
Steps taken to identify the issue
I've echoed the values that is passed through the url and only got "Food", with the rest of the string cut off. I've tried replacing the string values to Food and Beverage, and the whole thing works perfectly, leading me to conclude that the string is being cut off due to the ampersand(&) sign which causes the computer to treat the part of the string after the ampersand as another value to be passed through the URL.However, as i did not assign it to a variable, it is not being passed through.
Question
Is there any way for me to pass the value without it being cut off?
Code Extracts:
Processing Page
<?PHP
include("cxn.inc");
$query=$cxn->prepare("SELECT * FROM `BusinessSubCategory` WHERE `BusinessCategory`=:businesscategory");
$query->bindValue(":businesscategory",$_GET['category']);
$query->execute();
$count=$query->rowCount();
if($count>0)
{
echo"<option id='subcategory' value=''>Please select a SubCategory</option>";
while($result=$query->fetch(PDO::FETCH_ASSOC))
{
$subcategory=$result['BusinessSubCategory'];
echo"<option id=$subcategory value=$subcategory >$subcategory</option>";
}
}
else
{
echo"<option id='subcategory' value=''>Error,fetch query not run. </option>";
}
?>
JQuery Code
$(document).ready(function(){
$('#BusinessCreateCategory').load('getbusinesscategory.php');
$('#BusinessCreateCategory').change(function(){
var category=$('#BusinessCreateCategory').val();
window.location.href='getbusinesssubcategory.php?category='+category;
});
EDIT:Tried encodeURIComponent, but the data is not being encoded as i can see from the url of the processing apge that it is cut off at the ampersand.HOWEVER, if i were to manually enter the url as a string and then code it using encodeURIComponent, it works wonderfully.CAn anyone shed some light on why i am unable to encode $('#BusinessCreateCategory').val(); ? Thanks!
E.gThis works
var category="Food & Beverages";
var encoded =encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
E.g This does not
var category=$('#BusinessCreateCategory').val();
var encoded= encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
If it helps, the data i am trying to pass through the url is taken from my database.
You need to encodeURIComponent the value for category before using it in a URL.
$('#BusinessCreateCategory').change(function(){
var category=$('#BusinessCreateCategory').val();
var encoded = encodeURIComponent(category);
window.location.href='getbusinesssubcategory.php?category='+encoded;
});
Ampersand is a special character that garbles the URL you are trying to pass. Encoding the value should allow you to treat it as a single value.
There is a browser limit to how many characters can pass through. Do you have an example of the complete string that you are trying to pass? I would initially suspect that this could be an encoding issue.
encodeURIComponent to encode the string being passed.
The value should be encoded but when you query your db it might look for exact match, in case you fail to see any output via the encoded string use decodeURIComponent to decode the string before passing it to db. Check the output at phymyadmin before your formally put the code.

window.open(), browser address bar, and jQuery url decode

I am passing values in a URL query string that are interpreted by JavaScript and used to fill out form elements. The user click a link on one page, is taken to another page which then decodes the values from the URL and populates the form fields.
To decode the URL, I am using the jQuery URL Decoder plugin.
This is the parameter being passed to window.open():
http://mydomain.com/whatever?EmailAddress=me%40privacy.com&YourName=joe%20schmo&CompanyName=TEXAS%20A%20%26%20M%20-%20LUBBOCK%2C%20TX
When I plug that URL into the online version of the decoder, it is properly parsed - the querystring parameters are in the .params object, properly decoded.
However, after the link is clicked when I examine window.location.href, I get this:
http://mydomain.com/whatever?EmailAddress=me#privacy.com&YourName=joe%20schmo&CompanyName=TEXAS%20M%20&%20M%20-%20LUBBOCK,%20TX
Which comes out of the URL decoder as a giant mess (i.e. not properly decoded IMO because the input is not properly encoded).
How do I (safely) get back to string that's properly interpreted by the URL decoder?
use a javascript function like this:
function urlencode(str) {
return escape(str)
.replace(' ', '%20') // or replace with '+'
.replace('#', '%40');
}
(I know you don't need the first replace but this is more complete... you can add more replaces as you need them or search for a full urlencode)

Best way to safely read query string parameters?

We have a project that generates a code snippet that can be used on various other projects. The purpose of the code is to read two parameters from the query string and assign them to the "src" attribute of an iframe.
For example, the page at the URL http://oursite/Page.aspx?a=1&b=2 would have JavaScript in it to read the "a" and "b" parameters. The JavaScript would then set the "src" attribute of an iframe based on those parameters. For example, "<iframe src="http://someothersite/Page.aspx?a=1&b=2" />"
We're currently doing this with server-side code that uses Microsoft's Anti Cross-Scripting library to check the parameters. However, a new requirement has come stating that we need to use JavaScript, and that it can't use any third-party JavaScript tools (such as jQuery or Prototype).
One way I know of is to replace any instances of "<", single quote, and double quote from the parameters before using them, but that doesn't seem secure enough to me.
One of the parameters is always a "P" followed by 9 integers.
The other parameter is always 15 alpha-numeric characters.
(Thanks Liam for suggesting I make that clear).
Does anybody have any suggestions for us?
Thank you very much for your time.
Upadte Sep 2022: Most JS runtimes now have a URL type which exposes query parameters via the searchParams property.
You need to supply a base URL even if you just want to get URL parameters from a relative URL, but it's better than rolling your own.
let searchParams/*: URLSearchParams*/ = new URL(
myUrl,
// Supply a base URL whose scheme allows
// query parameters in case `myUrl` is scheme or
// path relative.
'http://example.com/'
).searchParams;
console.log(searchParams.get('paramName')); // One value
console.log(searchParams.getAll('paramName'));
The difference between .get and .getAll is that the second returns an array which can be important if the same parameter name is mentioned multiple time as in /path?foo=bar&foo=baz.
Don't use escape and unescape, use decodeURIComponent.
E.g.
function queryParameters(query) {
var keyValuePairs = query.split(/[&?]/g);
var params = {};
for (var i = 0, n = keyValuePairs.length; i < n; ++i) {
var m = keyValuePairs[i].match(/^([^=]+)(?:=([\s\S]*))?/);
if (m) {
var key = decodeURIComponent(m[1]);
(params[key] || (params[key] = [])).push(decodeURIComponent(m[2]));
}
}
return params;
}
and pass in document.location.search.
As far as turning < into <, that is not sufficient to make sure that the content can be safely injected into HTML without allowing script to run. Make sure you escape the following <, >, &, and ".
It will not guarantee that the parameters were not spoofed. If you need to verify that one of your servers generated the URL, do a search on URL signing.
Using a whitelist-approach would be better I guess.
Avoid only stripping out "bad" things. Strip out anything except for what you think is "safe".
Also I'd strongly encourage to do a HTMLEncode the Parameters. There should be plenty of Javascript functions that can this.
you can use javascript's escape() and unescape() functions.
Several things you should be doing:
Strictly whitelist your accepted values, according to type, format, range, etc
Explicitly blacklist certain characters (even though this is usually bypassable), IF your whitelist cannot be extremely tight.
Encode the values before output, if youre using Anti-XSS you already know that a simple HtmlEncode is not enough
Set the src property through the DOM - and not by generating HTML fragment
Use the dynamic value only as a querystring parameter, and not for arbitrary sites; i.e. hardcode the name of the server, target page, etc.
Is your site over SSL? If so, using a frame may cause inconsistencies with SSL UI...
Using named frames in general, can allow Frame Spoofing; if on a secure site, this may be a relevant attack vector (for use with phishing etc.)
You can use regular expressions to validate that you have a P followed by 9 integers and that you have 15 alphanumeric values. I think that book that I have at my desk of RegEx has some examples in JavaScript to help you.
Limiting the charset to only ASCII values will help, and follow all the advice above (whitelist, set src through DOM, etc.)

Categories

Resources