Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

window.location.href not working in form onsubmit

Tags:

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?

like image 364
Noura Avatar asked May 24 '11 11:05

Noura


3 Answers

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;
}
like image 188
Craig Avatar answered Oct 13 '22 21:10

Craig


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!

like image 26
Bret Weinraub Avatar answered Oct 13 '22 19:10

Bret Weinraub


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.

like image 1
pyathalon Avatar answered Oct 13 '22 20:10

pyathalon