如何在不重新加载页面的情况下更新和输出数据库?您要寻找的是 AJAX。
我知道您已经选择了答案,但是您需要一些额外的信息,从长远来看可能会对您有所帮助
你可以在网上学习一些很好的 ajax 教程
- Ajax Introduction
- What is Ajax ?
还有更多您可以在网上找到。
这是你需要做的,首先你的表单方法是GET,在你的php脚本中你请求一个$_POST,因此这将产生一个未定义的通知错误,changename:notice:未定义变量更改名称 所以解决方案是在单个表单中使用一种方法,如果您的表单是$_GET,您使用$variable = $_GET['fieldname'] 如果表单方法是POST 在您的服务器端使用$variable = $_POST['fieldname'];,而不是您的方式.因此,让我们将您的表单方法更改为POST 然后这就是您应该做的。
edit.php
更新
<script type="text/javascript">
$('document').ready(function(){
$('form').on('submit',function(event){
event.preventDefault();//prevent the form from reloading the page when submit
var formData = $('form').serialize(); // reading form input
$.ajax({
type :'POST',
data : formData,
url : 'profile.php',
dataType : 'json',
encode : true,
success : function(response){
//response = JSON.parse(response);
if(response == "ok"){
$('#success').html('profile updated success');
setTimeout(' window.location.href = "profile.php"; ', 6000); // redirecting
}else{
//could not update
$('#error').html(response);
}
},
error : function(e){
console.log(e); // debugging puporse only
}
});
});
});
</script>
这就是您在前端所需要的。请注意,如果您在一个页面中有多个表单,则不要使用$('form').on('submit',function(event){});,然后为每个表单指定一个唯一的ID,然后替换form在 jquery/ajax 上使用您要提交的表单的 iD。
然后是你的服务器端。
我注意到你有header('location: profile.php'); 那是
用于重定向,因为我们正在向服务器发送 ajax 请求,并且
回到客户端,你不会在服务器端重定向,你的
收到响应后使用客户端重定向
你期望从服务器。我已经评论了我做的那个部分
在上面的脚本中使用客户端重定向。
profile.php
<?php
$message = '';
if(isset($_POST['submit'])) {
require 'connect.php';
//validate your input field
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
$sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'";
if(mysqli_query($conn, $sql)){
$message = 'ok'; // success
}else{
$message = 'system error could not update please try again later';
}
echo json_encode($message);//sending response back to the client
mysqli_close($conn);
}
?>
这就是您所需要的,请注意,在使用之前,您需要在客户端和服务器端验证所有输入字段。
我还建议您了解有关准备好的语句的更多信息,使用 mysqli 或 PDO,它们非常易于使用且非常安全。
运行这样的查询:$sql = "UPDATE login SET login_name='$newname' WHERE user_id='$user_id'"; 非常不安全,您的输入没有经过验证,也没有经过过滤和清理。
所以使用准备好的语句很容易:
profile.php 准备好了
<?php
$message = '';
if(isset($_POST['submit'])) {
require 'connect.php';
//validate your input field
$newname = $_POST['changename'];
$user_id = $_SESSION['temp_user'];
//prepare and bind
$sql = $conn->prepare("UPDATE login SET login_name= ? WHERE user_id= ? ");
$sql->bind_param("si",$newname,$user_id);
if($sql->execute()){
$message = 'ok';
}else{
$message = 'Error Could not update please try again later';
}
echo json_encode($message);
$conn->close();
}
?>
$sql->bind_param("si",$newname,$user_id);这个函数将参数绑定到SQL查询,并告诉数据库参数是什么。
是。通过告诉mysql期望什么类型的数据,我们将SQL注入的风险降到最低。