Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript redirect not working anyway

There are many same questions here. I tried all solutions - nothing helps.

I want to open new page in some tab with javascript. Here is my HTML:

<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" ></script>
<script src="functions.js"></script>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<link href="css.css" rel="stylesheet" type="text/css" />

</head>
<body>
...
<label>
<input type="image" name="imageField" id="loginClient" onclick="testUrl()" src="images/index_33.gif" />
</label>
...
</body>
</html>

Here is my functions.js:

function testUrl()
{

window.location = "content.html";

}

function loginClient()
...//more functions

I tried other ways too:

window.location.replace("content.html")

top.location="content.html"

window.location.assign("content.html")

window.open("content.html", "_self")

window.location.href="content.html"

window.event.returnValue = false;
window.location = "content.html";

setTimeout(function(){window.location.assign("content.html");return false;},500)

nothing works, I tried it in Opera, Firefox (all in Windows) and Chrome (Debian). BUT it works if I set:

window.open("content.html")

but in new tab, isn't solution, I need it in same tab.

BUT if I try to debug it with Firebug and click always "Step into" than all solution work. And if I set alert() before redirecting, it works too.

Console shows no errors. I have no idea, help.

RESOLVED: Thanks to @lonesomeday!

this is the solution:

$(document).ready(function(){
    $("#loginClient").click(function(event){
      event.preventDefault();
      window.location = "content.html";
    });
});
like image 430
Alexander Tumanin Avatar asked Oct 22 '14 22:10

Alexander Tumanin


1 Answers

You've got this onclick attribute on an <input type="image"> element. Image inputs are effectively submit buttons. When you click it, it is activated, and the form is submitted. When a form is submitted, it cancels any ongoing HTTP requests, such as your window.location call.

So you need to prevent the form submission from going ahead.

The quick and dirty way to do this is to return false from your event handler. Something like this:

onclick="return testUrl()" 

With the JS:

function testUrl()
{
window.location = "content.html";    
return false;
}

The prettier way to do this would be to bind your event handlers with Javascript and use event.preventDefault.

like image 56
lonesomeday Avatar answered Oct 14 '22 03:10

lonesomeday