I'd use a self-submitting form like this:
<?php
function DB_Optimize() {
echo "function done";
}
if (isset($POST['do'])){
switch ($POST['do']) {
case "optimize":
DB_Optimize();
echo '<script language="javascript">
alert("Database has been optimized.");
</script>';
break;
}
}
echo "<form name='optimize' method='post' action='{$_SERVER['PHP_SELF']}'>
<input type='hidden' name='do' value='optimize'>
</form>
<a href='#' onclick='document.optimize.submit()'>Optimize Database</a>";
?>
OR if it's really important that this doesn't get submitted twice (by someone clicking refresh and saying yes to post data resubmission), I'd do it as you're doing it and at the end of the script have that redirect back with a header("location:test.php").
You can't echo anything before a redirect, so if you want a popup, send a flag header("location:test.php?flag=done") and do it when you come back.
if (isset($POST['flag']) && $POST['flag'] == "done"){
echo popup...
}