window.location.href not working in form onsubmit - javascript

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

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.

location.href could not load new location?

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.

Redirect and then alert

I'm processing something and when the function is successful I would like to redirect to another page and there show the alert "Function successful".
I'm using CodeIgniter, Javascript and Bootstrap
Any ideas will be appreciated
Once page X has redirected to page Y, page X is no longer open, so can no longer issue alerts. Your options include:
don't redirect. (Instead, you may be able to put page Y in an iframe; or, simply provide a link to it and let the user decide whether to click.)
don't alert.
alert before redirecting. (This is basically the same thing. The user can't actually interact with page Y until they've closed the alert, anyway, so it doesn't really matter whether the alert comes before or the redirect or after it.)
have page Y give the alert. For example, page X can redirect to http://example.com/path/to/Y/?alert=Function+successful, and you can design page Y to detect the query string and issue the alert.
When the functions is successful, redirect and use the body onload event of the new page. Using a querystring extraction based on another SO answer:
if (success)
{
window.location("anotherpage.html?myparm=alertMe");
}
...
anotherpage.html
<body onload="bodyLoad();">
...
</body>
<script type="text/javascript">
function bodyLoad()
{
parmValue = getParameterByName("myparm");
if(parmValue == 'alertMe')
{
alert('Function successful');
}
}
//http://stackoverflow.com/questions/901115/how-can-i-get-query-string-values
function getParameterByName(name) {
var match = RegExp('[?&]' + name + '=([^&]*)').exec(window.location.search);
return match && decodeURIComponent(match[1].replace(/\+/g, ' '));
}
</script>

URL redirect, but can't get it to save in browser history.

The code I've included below is meant to redirect to a new url if the user is not on a specific page or does not have a certain cookie. The cookie function works perfectly as does the redirect. Here is my problem: The window url redirects, but the original url is not logged in my browser history.
<script type="text/javascript">
$(document).ready(function() {
if (getCookie('legal_age') == "yes" || window.location =="http://example.com/home") {//user is legal age!
} else {
setTimeout(function() {
window.open('http://example.com/welcome','_self','', false);
},0)
}
});
</script>
For example, if I visit "http://example.com/page1", the browser redirects to "http://example.com/welcome", as it should. However, I need the original url visited ("http://example.com/page1") to show up in my browser history so that I can call upon it in a different function. Here is the code I am using to call the history (within a form):
<form action="javascript:window.location.reload(history.go(-1));" method="get" name="age_form" id="ageForm" />
I've also tried this alternative to call the history and it didn't help:
window.history.back();
I have also tried the following with no success in saving original url in browser history:
window.location = "http://example.com/welcome";
window.location.href = "http://example.com/welcome";
window.location.assign("http://example.com/welcome");
Finally, I included this function because another thread suggested it might help, but it hasn't seemed to do much:
setTimeout(function(){
Any ideas?
Is there anyway to get the original url visited to log in my browser's history before redirecting? HELP please!
setting a cookie of the current URL before redirecting worked well. Here is the altered code that worked. keep in mind that in order to set a cookie, you must reference a javascript cookie function (in this case mine is called setCookie():
<script type="text/javascript">
$(document).ready(function(){
if (getCookie('legal_age') == "yes" || window.location =="http://example.com/home") {//user is legal age!
} else {
setCookie('originalURL', window.location);
var urlCheck = getCookie('originalURL');
window.open('http://example.com/welcome','_self','', false);
}
});
</script>
Hope this helps someone!

Firefox 3.6 - location.href not working in JSP

I have JSP page with method = POST and action='/mydir/mypage/nextpage'
I have a button:
<button title='Continue' onclick="this.form.perform.value='cancelButton'; javascript:doCloseWindow();">Continue</button>
and JavaScript method like:
function doCloseWindow(){
location.href = "https://abc.xyz.com/mydir/?param=123";
}
It does not work in Firefox 3.6. On click of button; it redirects to the path I mentioned in form action.
With Tamper data I find that the request goes to URL (as in method) with GET and then it redirects to form's action URL.
I added return false in the method call also -- javascript:doCloseWindow();return false
I tired various combinations like
window.location.href = "https://abc.xyz.com/mydir/?param=123";
window.document.location.href = "https://abc.xyz.com/mydir/?param=123";
document.location.href = "https://abc.xyz.com/mydir/?param=123";
But no success.
Remove the "javascript:" before the call to doCloseWindow.
At this point, you've already executed some JavaScript code in this event handler — it doesn't make sense to try to tell the browser again that the following code is JavaScript.
Try changing your Javascript call to:
function doCloseWindow(){
alert('here');
location.href = "https://abc.xyz.com/mydir/?param=123";
return false;
}
I'm wondering if the function is actually running.

Categories

Resources