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

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)

Related

Cookie based on page path

Is it possible to set a cookie value, as the url page path?
i.e I have a cookie that is set when someone clicks a button with the ID mybtn but I'd like the value of the cookie to be automatically generated based on the last part of the page path. For example if the user clicked the button whilst on a page www.myweb.com/cars/car1 the value of the cookie should be set as car1. The code below is where I've got to so far, but it's the "THEPAGEPATH" where I'm stuck as I guess I need to use javascript to pull the url information.
<script>$("#mybtn").bind("click", function() {
document.cookie="model=THEPAGEPATH;path=/;"
});</script>
Simple solution would be to just split the string, and take the last part of it.
<script>$("#mybtn").bind("click", function() {
const strings = window.location.href.split("/").filter(str => !!str)
document.cookie=`model=${strings[strings.length - 1]};path=/;`
});</script>
This works for both routes with and without trailing slash. It does not work for routes that have query parameters that contains slashes. If you need to support that, you could split the string on ?, and the use the same logic on the first part of the string.

window.location.href not setting query parameters

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

HTML Append Variable to Query String

I have http://localhost/?val=1
When I click on a link, is there a way this link can append a query variable to the current string, for example:
Link
so when I click it the url would be:
http://localhost/?val=1&var2=2
but when I click the link it removes the first query string and looks like
http://localhost/&var2=2
Is such a thing possible with normal HTML?
You can't do that using only html, but you can do it with js or php:
Using JS:
<a onclick="window.location+=((window.location.href.indexOf('?')+1)?'':'?')+'&var2=2'">Link</a>
Using Php:
Link
Notice 1: make sure you don't have the new variable in the current link, or it'll be a loop of the same variable
Notice 2: this is not a professional way, but it could work if you need something fast.
Basically you want to get your current URL via JavaScript with:
var existingUrl = window.location.href; // http://localhost/?val=1
Then append any Query Strings that are applicable using:
window.location.href = existingUrl + '&var2=2';
or some other similar code. Take a look at this post about Query Parameters.
Note: A link would already have to exist with an OnClick event that calls a function with the above code in it for it to work appropriately.
Now obviously this isn't very useful information on it's own, so you are going to want to do some work either in JavaScript or in Server code (through use of NodeJS, PHP, or some other server-side language) to pass those variable names and their values down so that the button can do what you are wanting it to do.
You will have to have some logic to make sure the query parameters are put in the URL correctly though. I.E. if there is only one query param it's going to look like '?var1=1' and if it's any subsequent parameter it's going to look like '&var#=#'.

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.

passing hashtags as parameters to twitter

I have the following tweet:
var tweet = "I might actually do a 5K: http://t.co/tXQIYlUt #zombies #running"
And I would like to pass this to the twitter api using js
$('.my_div').append('Tweet')
My JS creates this: https://twitter.com/share?text=I%20might%20actually%20do%20a%205K:%20http://t.co/tXQIYlUt%20#zombies #running&via=JustinZollars&url=
which renders this way at twitter.com:
I might actually do a 5K: http://t.co/tXQIYlUt http://mydomain.com/
notice it cut out my hash tags. how can I sanitize my url?
Resources:
docs
encodeURIComponent() your GET param (the tweet variable). Also, don't encode the GET params that you do want to have special meaning (the & and =).
jsFiddle.

Categories

Resources