location.href could not load new location? - javascript

I need to redirect to new location when a button is clicked. I have used location.href=newloactionname.aspx but it doesn't move to new location. My code is:
function OpenUser(userID) {
location.href = 'UserRegistration.aspx?userID=' + userID;
alert(location.href)//shows only previous location
}

you can try:
window.location = 'UserRegistration.aspx?userID=' + userID;
instead...

See first if you have any javasript errors. Maybe your code does not calling OpenUser function.
Also try this:
//link click
window.location.href = "https://stackoverflow.com/";
OR
// HTTP redirect
window.location.replace("https://stackoverflow.com/");
I almost sure that you have an JS error somewhere. Press F12 on your browser.
Put an alert on the function. See if the alert appears.

Related

if confirm ignores location.href

The following code reloads the page rather than the desired URL
function delFile(name,id) {
if (confirm('Are you sure you want to DELETE '+name+'?')) {
location.href='/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id ;
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id);
}
else {
return false;
}
}
In the alert, the id is shown as being added properly and the URL is correct. I can copy it from the alert, then use that text to get the right result. Other scripts on the same page that use similar location.href are working perfectly but this is the only one using confirm.
I've also tried
window.location.href = "http://stackoverflow.com";
But the page still reloads.
The triggering link is:
onClick="return delFile('Bill','1234')
The href on the triggering link is still being linked to, because delFile() only returns false if the confirm is not accepted -- that's what's causing the page reload. When the function returns true, the link fires before the redirect occurs.
You want the function to return false in all cases, so don't put the return in an else clause.
function delFile(name, id) {
if (confirm('Are you sure you want to DELETE ' + name + '?')) {
location.href = '/cgi-bin/cnc.cgi?phrsrg~038919718485478~' + id;
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~' + id);
}
return false; // always, since you always want to prevent the link's default behavior. (Could also use event.preventDefault here.)
}
test
function delFile(name,id){
if (confirm('Are you sure you want to DELETE '+name+'?')) {
/* var fullpath = better to use the full url name/link;*/
var url = '/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id;
window.open(url, '_parent');
alert('/cgi-bin/cnc.cgi?phrsrg~038919718485478~'+id);
}
else {
return false;
}
}
It looks like the delFile() function is missing the opening curly brace, so I would start by fixing that. If the issue persists, check the JS console. Also, posting a codepen would be helpful.

Execute a function after changing location.href

I want to call a function after redirecting the page.
Inside my function I put a parameter which is an ID but when I check the console it wont display. I know I can be able to run it via on click event but I wont get the ID param from the previous page.
Is there a way to get it done?
Code:
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url; // new url
save(item_id); // call function after new url finish loading
});
}
function save(item_id){
console.log(item_id); // check if there's item_id exists
}
I agree with Katana's comment. Anything after your redirect statement will not run because the page itself is redirecting. One way that I would suggest to still get the item_id and get around that barrier, would be to include the item_id in the redirect url as a parameter. Then once on the new page, parse that parameter out of the url and save the item_id.
A great example from Cory Laviska's article on Parsing URLs in Javascript, shows how you can get the individual parameters from a URL.
Building onto Manish' answer:
Function on the current page:
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url+'?saved_item_id='+item_id; // new url
});
}
Function on the REDIRECTED Page (assuming you only have one parameter)
$( document ).ready(function() {
var url = $(this).data('url');
var item_id = url.queryKey['saved_item_id'];
save(item_id);
});
It may need a few tweeks because I didn't test the code, but hopefully it'll get you on the right track. :)
Hopefully this helps. If it helps and/or answers your question, please select as answer and up vote! :D Feel free to let me know if you have any questions
Try this one
The container is the section of your page where you perform an action.
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
$("#container").load(url,function(){
// other stuffs and functionalities
save(item_id); // call function after new url finish loading
});
});
}
You can try something like this.
function encode(item_id){
$('.js-encode').click(function(){
var url = $(this).data('url');
location.href = url+'?saved_item_id='+item_id; // new url
//save(item_id); // call function after new url finish loading
});
}
/*(function save(item_id){
console.log(item_id); // check if there's item_id exists
}*/
Further more , On New redirected URL you can get item_id which was appended to URL in previous page.
Hope this may help.

Window.Location Refreshes instead of Redirects

I have a JQUERY function as follows
this.getURL = function()
{
var name = getName();
alert("Menu.aspx?name"+name);
//window.location = "Menu.aspx?name"+name;
}
When I alert the URL I am attempting to go to, it is correct. However, when I call window.location on that string, the page just refreshes without going anywhere.
I have similar code where I have used window.location and it works. I typed in the url into my browser and it works as well.
At worst (even if the URL was wrong), I was hoping that it would just redirect me to some URL. However, I can't get it to do anything other than refresh the current page.
Also to clarify, the page which calls this function is not Menu.aspx
Thanks in advance.
If you're using a relative path try setting window.location.pathname, otherwise set window.location.href for a full path.
You may also want to try self.location.href
In my experience, it's been difficult to get redirects like this to work right. I've had to use window.location.replace(<url>). If you're just changing an anchor tag, it's even more difficult. You have to do the following to get it to work in all browsers:
window.location.replace(<url>);
window.location=<url>;
window.open(<url>,'_self');
window.location.reload();

window.location.href not working in form onsubmit

So i have a form, and onsubmit="return reg_check(this)" where reg_check() is a javascript function in the header which is supposed to check the form data, and since one of its tasks is to check if the username is in the database which requires php, i want to redirect to a php page that does this task.
Problem is: window.location.href is not working! Here's the function (reduced version) and of course the main.php is just a random page i got:
function reg_check(myForm) {
alert("before redirect..");
window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
alert("after redirect..");
}
The before redirect and after redirect alerts work, it just doesn't redirect? It remains in the same page.
Also, if I tried to redirect from the body by just typing :
<script type="text/javascript">
alert("before redirect..");
window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
alert("after redirect..");
</script>
it redirects.
Any ideas of how I could get this to work?
You need to return false; from your reg_check function and then in your onsubmit, change it to:
onsubmit="return reg_check(this);"
This will cancel the form submission. And if you want to let the form submit as normal, just return true from reg_check.
Edit (to be more clear you need to add return false; from your function):
function reg_check(myForm) {
alert("before redirect..");
window.location.href = "http://localhost/main.php?width=" + screen.width + "&height=" + screen.height;
return false;
}
I've seen problems in IE where I've had to do the following:
window.location.assign(url);
Specifically within a jQuery AJAX success handler. Can't really speculate to why other than for me, it worked.
Actually I did
window.location.replace(url)
Which replaces the current page in the history. Nice trick that!
I had the same problem, but found the answer here Javascript: window.location.href doesn't redirect when calling function within a function .
My button was reloading the page by default so if you add an
event.PreventDefault();
To your function it should work.
[RESOLVED] I had a similar problem in redirecting to some other url from client script. Implemented window.open function instead and it worked. You may have for instance, a function say ChangeCity() for your html control event that gets called with onchange event.
function ChangeCity() {
switch ($("#currentCity").val()) {
case "NY":
var url = '#Url.Action("New York City", "Home", new { #area = "" },Request.Url.Scheme)';
window.location.href = url;
window.open(url,"_top");
return false;
/* cases for other cities */
}
You may like to explore details on window.location.href redirection -Alternative Solution

Response.Redirect AFTER call to JS Alert or Confirm

I am working on a VB.NET web application. When someone successfully changes their password I want to show a popup message that lets them know it was changed successfully. After they click OK I want to redirect them to the main page. Code looks like this:
ClientScript.RegisterStartupScript(Me.GetType(), "confirmScript", "ConfirmNewUser();", True)
Response.Redirect("MainPage.aspx")
Why does the redirect happen and the alert popup never displays?
Try this:
1) Remove Response.Redirect from the code behind.
2) Change the ConfirmNewUser function as given below:
function ConfirmNewUser(){
//Existing Code of ConfirmNewUser
//New Code.
var msg = "Password changed successfully. Press OK to go to Home page Cancel to stay on current page.";
if(confirm(msg)){
window.location.href = "MainPage.aspx";
}
}
You are calling the redirect server side, your script never get a chance to run. use window.location to do the redirect client side, something like this:
function ConfirmNewUser() {
if(confirm("Your password has been changed, click OK to continue")) {
window.location = "MainPage.aspx"; //go to home page
}
}
The reason is because all server-side processing will take place prior to client-side.
One solution would be to pass "MainPage.aspx" to your client script as follows:
ConfirmNewUser('MainPage.aspx');
Your client script would then have to take a URL parameter:
function ConfirmNewUser(url) { ... }
and follow up with a window.location:
...
if(confirm(...))
{
window.location = url;
}
and remove the following from your server code:
Response.Redirect("MainPage.aspx")
Response.Redirect sets the Location http header and a 302-Moved response, the browser will act upon this as soon as it sees it. As headers come before content, your script is never seen or parsed.

Categories

Resources