How to make use of URL that was saved in cookie? - javascript

I am saving a URL in a cookie using Angular
$cookies.put("targetURL": "http://partners.api.xyz.net/apiservices/deeplink/v2?_cje=TmvlUQgTj%2fbxOQ%2bkXy5haJR9JWcHT9aaSjEP%2fEbwSq4uZqOYt%2fRV9FYsU1PT80PD&url=http%3a%2f%2fwww.apideeplink.com%26cabin_class%3deconomy%26facilitated%3dfalse%26ticket_price%3d72.82%26is_npt%3dfalse%26is_multipart%3dfalse%26client_id%3d2017-02-22T10%3a02%3a07")
However, I have to retrieve this cookie with plain javascript. When I try to get it, the string is transformed into
"http%3A%2F%2Fpartners.api.xyz.net%2Fapiservices%2Fdeeplink%2Fv2%3F_cje%3DTmvlUQgTj%252fbxOQ%252bkXy5haJR9JWcHT9aaSjEP%252fEbwSq4uZqOYt%252fRV9FYsU1PT80PD%26url%3Dhttp%253a%252f%252fwww.apideeplink.com%2526cabin_class%253deconomy%2526facilitated%253dfalse%2…e%2526is_multipart%253dfalse%2526client_id%253d2017-02-22T10%253a02%253a07" and not clickable anymore.
To retrieve the cookie I am using the function:
function getCookie(name) {
var value = "; " + document.cookie;
var parts = value.split("; " + name + "=");
if (parts.length == 2) return parts.pop().split(";").shift();
}
Why is the string changed like this and what can I do to solve this?

You need to decode the URI with decodeURIComponent()
old = "http%3A%2F%2F";
new = decodeURIComponent( old );
#new => http://

Related

how to prevent new element being appended repeatedly in javascript function?

Currently I have a JavaScript function like this:
<script type="text/javascript">
function select_device(device)
{
var mylink = window.location.href + "&name=" + device.value;
window.location.replace(mylink);
window.history.back
}
</script>
When a variable pass in, it will add as a new element into the url. Is there any way that I could possibly pass the variable in smartly as it will not just append repeatedly to the existing address?
I have tried to do it like
const url = window.location
window.location.replace(url.hostname + url.pathname + url.search + "&name=" + device.value)
But it doesn't solve the problem.
Since it sounds like you have multiple search parameters, not just name (since you're using &, not ? at the beginning), use URLSearchParams from the search string, set the new name, and then turn it back into a string:
function select_device(device) {
const { pathname, search } = window.location;
const params = new URLSearchParams(search);
params.set('name', device);
window.location.replace(pathname + '?' + String(params))
}

Add a variable in URL instead of replacing one

I'm facing a little issue with a javascript script. I'm trying to make my website multi languages. All is set in database, and my select works on pages where the URLs don't have variables. Here is my script:
<script type="text/javascript">
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
window.location.href = window.location.pathname + '?lang=' + thelang;
}
</script>
In the homepage case, it works, and change http://localhost/ by http://localhost/?lang=en
But when I have an URL with a variable already set, it replaces it. From http://localhost/modules/product/product.php?id=1 I have http://localhost/modules/product/product.php?lang=en and the result I'd like is:
http://localhost/modules/product/product.php?id=1&lang=en
How to fix the script to make it works in both cases, or add the varibale, or glue it with an existing one?
Try checking to see if querystring params already exist in the URL.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
if (window.location.href.indexOf('?') >= 0) {
// There are already querystring params in the URL. Append my new param.
window.location.href = window.location.href + '&lang=' + thelang;
} else {
// There are not querystring params in the URL. Create my new param.
window.location.href = window.location.href + '?lang=' + thelang;
}
}
Update: Account for Subsequent Lang Changes
This assumes that the lang value will always be two characters.
function submitForm() {
var thelang = document.getElementById('lang').options[document.getElementById('lang').selectedIndex].value;
var newUrl = window.location.href;
var langIndex = newUrl.indexOf('lang=');
if (langIndex >= 0) {
// Lang is already in the querystring params. Remove it.
newUrl = newUrl.substr(0, langIndex) + newUrl.substring(langIndex + 8); // 8 is length of lang key/value pair + 1.
}
// Remove the final '?' or '&' character if there are no params remaining.
newUrl = newUrl.endsWith('?') || newUrl.endsWith('&') ? newUrl.substr(0, newUrl.length - 1) : newUrl;
newUrl = newUrl.indexOf('?') >= 0
? newUrl + '&lang=' + thelang // There are already querystring params in the URL. Append my new param.
: newUrl + '?lang=' + thelang; // There are not querystring params in the URL. Create my new param.
window.location.href = newUrl;
}
If I understand you correctly you want to add ?lang=en at the end. Unless there is already an id=1(or similar) there.
So you could just add an if statement, looking if there is .php writen at the end.
Not a very pretty solution but you are alreaady adding strings together so it doesn't matter
You can use the "search" element of window.location. See here for compatibility. You can then, concat the result with your desired parameter. BUT, you can do something way more complex (and secure) and check if there's already a parameter with that ID using a for + URLSearchParams.
const params = new URLSearchParams(window.location.search);
const paramsObj = Array.from(params.keys()).reduce(
(acc, val) => ({ ...acc, [val]: params.get(val) }), {}
);
This should fix it:
var currentUrl = window.location.origin + window.location.pathname;
var newUrl = currentUrl + (currentUrl.includes('?') ? ('&lang=' + thelang) : ('?lang=' + thelang));
window.location.href = newUrl;

indexOf() in javascript

Okay so i have started learning javascript from the book Beginning Javascript 5th ed, just confused by a js script
function getCookieValue(name) {
var value = document.cookie;
var cookieStartsAt = value.indexOf(" " + name + "=");
if (cookieStartsAt == -1) {
cookieStartsAt = value.indexOf(name + "=");
}
if (cookieStartsAt == -1) {
value = null;
} else {
cookieStartsAt = value.indexOf("=", cookieStartsAt) + 1;
var cookieEndsAt = value.indexOf(";", cookieStartsAt);
if (cookieEndsAt == -1) {
cookieEndsAt = value.length;
}
value = unescape(value.substring(cookieStartsAt,
cookieEndsAt));
}
return value;}
My question is how does the indexOf operator works here( i know how it works and used it previously) ??
The above program is defined below by the book which goes as :
The first task of the function is to get the document.cookie string and store it in the value variable
var value = document.cookie;
Next, you need to find out where the cookie with the name passed as a parameter to the function
is within the
value string. You use the inde x Of() method of the String object to find this
information, as shown in the following line:
var cookieStartsAt = value.indexOf(" " + name + "=");
The method will return either the character position where the individual cookie is found or ‐1 if no
such name, and therefore no such cookie, exists. You search on
" " + name + "=" so that you don’inadvertently find cookie names or values containing the name that you require. For example, if you
have
xFoo, Foo, and yFoo as cookie names, a search for Foo without a space in front would match
xFoo first, which is not what you want!
What the just just happened here?? How did they achieve the location of the name using indexOf() ?? please explain ? I couldn't understand the xfoo,foo,yfoo example ?? Looking for a simpler example.
document.cookie contains a string like cookiename=cookievalue
indexOf is getting the position of the begining of the value part of the cookie
var cookieStartsAt = value.indexOf("cookiename=");
That allows you to use that number to get the value portion of the string with substring()

Define session variable in c# get it from javascript

I'm saving string that represents the URL in a session variable from my code behind like this:
String mois = Request.QueryString["mois"].ToString();
String m = mois;
String moisnom = Request.QueryString["moisnom"].ToString();
String annee = Request.QueryString["annee"].ToString();
String dt = Request.QueryString["date"].ToString();
String user = Request.QueryString["user"].ToString();
String where = "jour.aspx?mois=" + mois + "&moisnom=" + moisnom + "&annee=" + annee + "&date=" + dt + "&user=" + user + "&cp=all" + "&usl=" + Request.QueryString["usl"].ToString();
Session["togo"] = where;
And then I try to get it like this in JavaScript like this:
var togo = '<%=Session["togo"]%>';
// i also tried this var togo ='#Session["togo"]';
var newPage = togo; // this should contain a string with the url to go to
But when I use it it uses it as a string here is what my URL looks like:
http://localhost:50311/<%=Session["togo"]%>
or
http://localhost:50311/#Session["togo"]
How else can I access the session variable or what am I doing wrong please?
EDIT:
like you suggested i already tried using the hidden field like this
yes i tried that but then i had this problem here is the definition of the hidden field
<input type="hidden" value="aa" id="myHiddenVar" runat="server"/>
then i tried giving it the value i need on click
String where = "jour.aspx?mois=" + mois + "&moisnom=" + moisnom + "&annee=" + annee + "&date=" + dt + "&user=" + user + "&cp=all" + "&usl=" + Request.QueryString["usl"].ToString();
myHiddenVar.Value= where;
and this is how i tried getting it from the js file
var togo = $('#myHiddenVar').val();
var newPage = togo;
but it takes the default value meaning "aa" as in value="aa" i gues cause the script is executed before the assignment of the variable any way how to reverse that order ?
After Session["togo"] = where;
save this Session["togo"] in hidden variable
hiddenVariable= Session["togo"];
Now in JS access that hiddenvariable:
suppose ID of hiddenvariable is "hdnxyz"
var togo = $('#hdnxyz').val();
var newPage = togo;
first of all session resides on server!!!!!!
If it is in different js file than you cant access it <%xyz%> i.e scriplet tags only work on aspx page...
so there is no way to access the session variable on client side..
instead assign your sessio9n value to a hidden variable and then access it using javascript
Write Session element in a asp:HiddenField and then read from it with your js code.

using 'location.href' to pass variable

I've found several posts alluding to the location.href method. But I can't find anything about how to use the variable on the next page that's opened.
I have a function with a single line of code in an external js file:
function nextPage()
{location.href='page2.html?foo=' + src;}
It's activated by a button in the html file. How do I use this on the next page that's opened? I'm assuming this makes 'foo' available. ('src' is an integer stored as a global variable in the external js file. It's just a number between 1 and 5).
On the next page you can get the value using:
http://page2.html?foo=
location.search
> ?foo=
location.search.substring(1)
> foo=
In Script Tag You Put
var array=location.search;
var data = array.split("foo=");
var divid=data[1];//It has your foo value
if you are using javascript then try this code to get querystring value
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, " "));
}
var value = getParameterByName('foo');

Categories