[php] How to close Browser Tab After Submitting a Form?

<?php
    /* ... SQL EXECUTION TO UPDATE DB ... */
?>

<form method  = "post"
      action  = "<?=$_SERVER['php_self']?>" 
      onSubmit= "window.close();">
  ...
  <input type="submit" value="submit" />
  <input type="reset"  value="reset" />
</form>

I would like to close page after submitting the form. After running the above code the page is closed after clicking submit button, but the SQL doesn't execute.

Can anyone help me? Thanks in advance!

This question is related to php javascript

The answer is


This worked brilliantly for me, :

 $query = "INSERT INTO `table` (...or put your preferred sql stuff)" 
 $result = mysqli_query($connect, $query); 
 if($result){
  // If everything runs fine with your sql query you will see a message and then the window
  //closes
        echo '<script language="javascript">';
        echo 'alert("Successful!")';
        echo '</script>';
        echo "<script>window.close();</script>";
        }
 else {
        echo '<script language="javascript">';
        echo 'alert("Problem with database or something!")';
        echo '</script>';           
        }

You can try this methods

window.open(location, '_self').close();

Remove onsubmit from the form tag. Change this:

<input type="submit" value="submit" />

To:

<input type="submit" value="submit" name='btnSub' />

And write this:

if(isset($_POST['btnSub']))
    echo "<script>window.close();</script>";

That's because the event onsubmit is triggered before the form is submitted.

Remove your onSubmit and output that JavaScript in your PHP script after you have processed the request. You are closing the window right now, and cancelling the request to your server.


try onsubmit="submit(); window.close()"


If you have to use the same page as the action, you cannot use onSubmit="window.close();" as it will close the window before the response is received. You have to dinamycally output a JS snippet that closes the window after the SQL data is processed. It would however be far more elegant to use another page as the form action.


Window.close( ) does not work as it used to. Can be seen here:

window.close and self.close do not close the window in Chrome

In my case, I realized that I didn't need to close the page. So you can redirect the user to another page with:

window.location.replace("https://stackoverflow.com/");