简体   繁体   中英

How Can i redirect to another PHP Page when i Confirm using Javascript without using PHP header Function

I have PHP page called Course Enrollment where the student can enrol in a course or cancel his enrollment. when the user cancel his enrollment I made a javascript function called confirmDelete() that send a confirmation message before deletion. if the user pressed OK then it will redirect the user to deleteEnrollment.php (where I execute the deletion) if the user pressed cancel then do nothing.

The Course_Enrollment.php has the below code

<SCRIPT language=JavaScript>

function confirmDelete() {
  if (confirm("Do you really want to delete your Enrollment?")) {
    window.location.href = "includes/deleteEnrollment.php";
    return;
  } 
}
  </script>
 <form action="" method="post" role="form">
              <button type="submit" name="cancel" class="btn btn-primary" onclick="confirmDelete()">Cancel Enrollment</button>

when I run the above code nothing happened. i don't know the reason. when I change window.location.href with header("location:includes/deleteEnrollment.php");it works fine but I don't want to use header because if the user press yes or no the PHP code will execute.

Where is the issue in my code?..


<form action="" method="post" role="form">
    <button type="submit" name="cancel" class="btn btn-primary" onclick="return confirmDelete()">Cancel Enrollment</button>
</form>

<script type="application/javascript">
function confirmDelete() {
    if (confirm("Do you really want to delete your Enrollment?")) {
        window.location.href = "includes/deleteEnrollment.php";
        return false;
    }
    return false;
}
</script>

Add return to onclick and also add return to JavaScript function.

See it in action.

You are not submitting any form data with that button so the button type should not be submit . Change the button type to button or reset and it will work, eg: type="button" . Also, you don't need the return statement.

This has already been answered: window.location.href doesn't redirect

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM