JavaScript/PHP:成功保存后的弹出对话框

3

我是编程新手。目前,我正在开发一个具有注册功能的系统,并成功将注册信息保存到数据库中。我想知道如何在注册成功后弹出一个带有一个按钮(例如“确定”)的警告对话框,并重定向到另一个页面,例如主页。现在我只能输出“保存成功”。

以下是我的当前代码

<?php
require "DbConnect.php";
    $name = $_POST['name'];
    $badgeid = $_POST['badgeid'];
    $position = $_POST['position'];
    $department = $_POST['department'];
    $factory = $_POST['factory'];
    $reviewer = $_POST['reviewer'];
    $title = $_POST['title'];
    $year = $_POST['year'];
    $month = $_POST['month'];
    $suggestionwill = $_POST['suggestionwill'];
    $present = $_POST['present'];
    $details = $_POST['details'];
    $benefit = $_POST['benefit'];


$sql_query = "INSERT INTO topsuggest (name,badgeid,position,department,factory,
reviewer,title,year,month,suggestionwill,present,details,benefit) VALUES('$name','$badgeid','$position','$department','$factory','$reviewer','$title','$year','$month','$suggestionwill','$present','$details','$benefit')";

if(mysqli_query($conn,$sql_query))
{
echo "<p id='msg'></p>";
}
else
{
echo "Error!! Not Saved".mysqli_error($con);
}

?>

1
你可以使用ajax请求来完成。停止表单提交的默认事件,并使用JS显示ajax消息。例如:http://api.jquery.com/jquery.ajax/ 或 https://reactjs.org/docs/faq-ajax.html 或查看纯JS https://www.w3schools.com/js/js_ajax_examples.asp 请求。并注意在SQL字符串中转义变量 https://www.php.net/manual/de/mysqli.real-escape-string.php。 - Richard
2个回答

1

只需使用php header函数并使用javascript弹出一个消息。

      if(mysqli_query($conn,$sql_query))
    {
    echo "<script>alert('Successfuly Saved');</script>";
 header('Location: PATH TO BE REDIRECTED');
    }

例如

if(mysqli_query($conn,$sql_query))
    {
    echo "<script>alert('Successfuly Saved');</script>";
 header('Location: ../Insert/Index.php');
    }

请注意,"Location:" 后面的空格是必须的。

1
这里没有带有“确定”按钮的“对话框”,你可以将其转发到另一个页面。 - Richard
@Richard 是的,你说得对。所以我已经更新了我的答案。谢谢。 - Nipun Tharuksha
@F.Lampard 如果你找到了答案,请将其标记为答案。谢谢。 - Nipun Tharuksha

1

插入数据后,您可以简单地重定向到感兴趣的页面,并显示成功消息,例如:

header("location:page_of_interest.php?msg=Record Inserted");

page_of_interest.php页面上,您可以简单地检查msg是否设置,如下所示:
if(isset($_GET['msg'])){
  echo $_GET['msg'];
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接