Home > Back-end >  How Can i redirect to another PHP Page when i Confirm using Javascript without using PHP header Func
How Can i redirect to another PHP Page when i Confirm using Javascript without using PHP header Func

Time:11-24

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?..

CodePudding user response:


<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.

CodePudding user response:

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, e.g.: type="button". Also, you don't need the return statement.

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

  • Related