Sweety Mouni
Sweety Mouni

Reputation: 51

Confirm/redirect functionality not working - javascript

Here I used JavaScript to Delete an employee...

<script type="text/javascript">
function delet(emp)
{
    var answer = confirm('Are you sure?');
    if(answer)
    {
        window.location='delete.php?emp='+emp;
    }
}
</script>

By using anchor tag am calling the function of javascript ....

<a onclick="javascript:delet('<? echo $_GET['emp']; ?>')">
<input type="button" name="delete" id="delete" style="background: url('images/del1.jpg')no-repeat;width:50px;height:50px" value=""/></a>           

But my problem is it is working upto showing the alert msg but after answering the alert msg it is not redirecting to the page given by me that is "delete.php?emp=+emp"

Upvotes: 1

Views: 260

Answers (2)

Bergi
Bergi

Reputation: 664538

You're submitting some form by clicking on that button. That submit process will overrule the window.location navigation request. A quick workaround would be to prevent that:

<a onclick="event.preventDefault(); delet('<? echo $_GET['emp']; ?>');">
// cross-browser-safe:
<a onclick="delet('<? echo $_GET['emp']; ?>'); return false">

but actually your markup with the nested button is quite odd. You don't need that link at all, just use

<form action="delete.php" onsubmit="return confirm('Are you sure');">
    <input type="hidden" name="emp" value="<? echo $_GET['emp']; ?>" />
    <input type="submit" name="delete" id="delete" style="background: url('images/del1.jpg')no-repeat;width:50px;height:50px" value="" />
</form>

Upvotes: 0

Paul S.
Paul S.

Reputation: 66334

Because you're nesting an <input type="Submit"/> inside an <a>, clicking the button is not the same as clicking the <a>, rather it "Submits" nowhere (read to the page you're already on, refreshing the page) before the <a> can do it's job.

Simple demo where you don't go to google.

<a href="http://google.com/"><input type="Submit"/></a>

Bergi has pointed out that the behaviour I described is not universal (hello Opera, IE) unless a <form> element is present, so for example the following

<form action="jail.php">
    <a href="go.php" onclick="window.location='?collect=£200';">
        <input type="submit"/>
    </a>
</form>

will send you directly to jail without passing go or collecting £200 across all browsers.

Further, this only really applies to page redirection; other pieces of script may well fire before the page changes, the easiest to observe being console.log, alert, etc.

Upvotes: 7

Related Questions