Redirect in Javascript with multiple query params - javascript

I have this code :
if($('#category').val() == 4){
console.log("http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'?week_id='+$('#week_id').val()+'?year_id='+$('#year_id').val());
window.location = "http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'?week_id='+$('#week_id').val()+'?year_id='+$('#year_id').val();
}
In the console I have
http://myWebsite.dev/dailyGift?id_event=41?week_id=44?year_id=2016.
When I access directly works without problems, but jQuery does not make this redirect and I don't understand where is the problem.

You need to change all the ? with & except the first one
if($('#category').val() == 4){
console.log("http://"+window.location.hostname+'/dailyGift?id_event='+$( "#sub-category" ).val()+'&week_id='+$('#week_id').val()+'&year_id='+$('#year_id').val());
}

Please replace all "?" with "&", Correct URL would be :-
http://myWebsite.dev/dailyGift?id_event=41&week_id=44&year_id=2016
Also it would be good if you encrypt ids for security purpose.

You say that you want to redirect to a link but you're merely changing the location.href value which is equivalent to clicking a link.
Location.replace() will load the new resource in place of the current one. The current page will not be added to the session history so it will not be possible to return to it using the back button.
I've also cleaned up the use of " and ' in the url string to make it cleaner.
if ($('#category').val() == 4){
var url = "http://"+window.location.hostname+"/dailyGift?id_event="+$('#sub-category').val()+"&week_id="+$('#week_id').val()+"&year_id="+$('#year_id').val();
console.log(url);
window.location.replace(url);
}

Related

Why is window.location.href appending url again

In my code, I'm assigning the following:
window.location.href = "www.example.com/test";
But when the page actually loads, the browser URL is www.example.com/test/www.example.com/test. I'm not appending anything to the URL, and I'm not sure how its appending the URL again.
I think you're missing the "http" or "https" part. Have you tried the following?
window.location.href = "https://www.example.com/test";
or
window.location.href = "http://www.example.com/test";
Because you forgot the protocol. If you omit the protocol, window.location.href thinks you are trying to access a folder with the name of www.example.com, relative to the page you are currently on.
window.location.href="http://www.example.com/test/" will ensure that you access the external website www.example.com.
Hope this helps! :)
Check the way you are constructing the url, sometimes we miss the host, or enter the incorrect path
A safe way to change the URl is by making changes in the exisiting URL
first get the existing URL by
let exisitingURl = window.location.href;
now manipulate this url, for eg
exisitingURL = exisitingURL.replace('/auth', '/gateway');
now go to the url by
window.location.href = existingURL;

Remove parameter from url not working

I'm attempting to remove a url parameter status from the url but in the following alert, the parameter is still there.
var addressurl = location.href.replace(separator + "status=([^&]$|[^&]*)/i", "");
alert(addressurl);
location.href= addressurl;
How do i solve?
You are confusing regex with strings.
It should be:
var addressurl = location.href.replace(separator, '').replace(/status=([^&]$|[^&]*)/i", "");
Javascript context in web pages are to the page you are working on.
When you reload, redirect or move to any other page, javascript changes done in previous page will not be there. This has to be handled from server side.
Refresh repeats the last request to the server, which is going to ignore your javascript changes. Instead navigate to the new url with window.location = addressurl;

taking the # out of url on location.hash

function updateView(category) {
console.log( window.location.hash );
if (location.hash !== ""){
//convert #3 to 3.
//load video based on id
//myArray[sanitizedHash];
} else {
updateCategoryLabel(category);
currentList = updateVideosList(category);
chooseRandomVideoFromList();
}
}
This function is loaded on page load
How can I parse inside this function so that the the location.hash's '#' will be taken out of the URL?
In short I am trying to achieve www.mysite.com/3 versus www.mysite.com/#3
Thanks in advance!
Edit: I should add that the 'else' is basically randomizing on page load versus going to the direct url. This if statement will run on page load to check if the hash exists otherwise it will randomize as usual.
Altering the URL from 'www.mysite.com/#3' to 'www.mysite.com/3' will cause the browser to navigate to a new URL since www.mysite.com/3 is not the same page as www.mysite.com/#whatever.
If you just want a string with the first character of the hash trimmed try:
window.location.hash.substr(1)
You can get the window.location.hash and then replace the # with an empty string
if (location.hash !== ""){
var sanitizedHash = window.location.hash.replace("#", "");
//load video based on id
//myArray[sanitizedHash];
}
If your goal is NOT to trigger page load, you can use HTML5 History API to change URL from www.mysite.com/#3 to www.mysite.com/3 like that:
var id = location.hash.substr(1);
history.replaceState({id:id}, id, id);
Note that replaceState is used, because otherwise user can press back button to the browser and get back to the #3. If you want to allow that, replace replaceState with pushState. Hope that helps.

JavaScript issue with matching URL

How can I add something in JavaScript that will check the web site URL of someone on a web site and then redirect to a certain page on the web site, if a match is found? For example...
The string we want to check for, will be mydirectory, so if someone went to example.com/mydirectory/anyfile.php or even example.com/mydirectory/index.php, JavaScript would then redirect their page / url to example.com/index.php because it has mydirectory in the url, otherwise if no match is found, don't redirect, I'm using the code below:
var search2 = 'mydirectory';
var redirect2 = 'http://example.com/index.php'
if (document.URL.substr(search2) !== -1)
document.location = redirect2
The problem with that, is that it always redirects for me even though there is no match found, does anyone know what's going wrong and is there a faster / better way of doing this?
Use String.indexOf() instead:
if (window.location.pathname.indexOf('searchTerm') !== -1) {
// a match was found, redirect to your new url
window.location.href = newUrl;
}
substr is not what you need in this situation, it extracts substrings out of a string. Instead use indexOf:
if(window.location.pathname.indexOf(search2) !== -1) {
window.location = redirect2;
}
If possible it's better to do this redirect on the server side. It will always work, be more search engine friendly and faster. If your users have JavaScript disabled, they won't get redirected.

JavaScript to reload the page as GET request

I have a seemingly simple question, but can't find the answer. I have a webpage, which may have resulted from a POST request and may have an anchor (#) in the URL. I want to reload this page as a GET request in JavaScript. So it's similar to this question, but I actually want to avoid the POST, not just the warning about it.
So, for example, if the page resulted from a POST request to "http://server/do/some?thing#" I want to reload the URL "http://server/do/some?thing" as a GET. If I try
window.location.reload(true);
that causes IE to try a POST. If I instead do:
window.location = window.location.href;
this does nothing when the URL has an anchor. Do I really need to do string manipulation myself to get rid of the "#whatever" or is there an easier, "better" way to do this?
The best I've come up with so far is:
function reloadAsGet()
{
var loc = window.location;
window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search;
}
Try the following:
location.replace(location.href)
You can try this
location=location.href

Categories