通过PHP验证显示表单提交的数据值,而无需刷新 [英] Show form submitted data values with PHP validation without refresh
问题描述
我试图弄清楚如何在通过HTML表单提交并存储为cookie的情况下使一些数据在提交后立即可供编辑...
I'm trying to figure out how to make some data available for editing right after submission when it is submitted via HTML form and stored as a cookie...
最上方,表单验证:
<?php
//check if form was sent
if(isset($_POST['send'])){
//some basic validation
if(strlen($_POST['myname']) > 2){
//set the cookie if passed
setcookie('myname', $_POST['myname']);
}
}
//set error if didn't pass validation
else {
$error[] = 'Your name is required!';
}
?>
因此,如果用户发布数据,它将捕获该数据并将其存储在Cookie中. 如果没有,则会出现错误:
So if a user posts data it will catch it and store it in a cookie. and If not, an error will be given:
<?php
//check for errors
if(isset($error)){
foreach($error as $error){
echo '<p style="background: red;">'.$error.'</p>';
}
}
?>
带有PHP的HTML表单:
<form method="post">
<input name="myname" type="text" value="<?php if(isset($_COOKIE["myname"])){
echo $_COOKIE["myname"];} ?>" placeholder="Your Name">
<input name="send" type="submit" value="send">
</form>
这用于收集数据并将其发送以通过PHP验证以设置cookie.如果cookie已经设置,则我希望它使用内联PHP代码显示该值.
This used for collecting data and sending it to pass PHP validation in order to set a cookie. if the cookie is already set, I want it to show the value with the inline PHP code.
发生的事情是,当提交表单时,存储了cookie,但是用户只有刷新页面后才能看到它,我可以添加header("Refresh:0");但这并不能解决问题,因为刷新时不会显示错误消息.
What happens is when the form is submitted the cookie is stored but the user will can see it only after refreshing the page, I could add header("Refresh:0"); but it doesn't solves the problem since the error massage will not show when refreshed.
我需要将其用于少数几种形式,因此目前我正在寻找一种快速简单的PHP解决方案,但它也可能是合适的Jquery/AJAX代码段.
I need to use it for few of those forms so currently I'm looking for a fast and simple solution in PHP but it can also be a suitable Jquery/AJAX snippet.
推荐答案
在Web2中,我们可以使用AJAX做到这一点.只需在表单sumbit上按ajax,然后
In Web2, We can do this by using AJAX. Simply hit ajax on form sumbit and
$('#submit_btn').on('click', function (e) {
e.preventDefault();
var $this = $('#form_id');
$.ajax({
url: 'setcookie.php',
data: $this.serialize(),
dataType: 'html',
type: 'POST',
beforeSend: function () {
// show loader
},
success: function (html) {
// Show success message
// Set value of input elements by reading cookie in JS
},
error: function () {
// Show ValidationError
}
}); });
在cookie.php中,将服务器端验证置于表单输入中.如果您想在同一页面上放置代码,也可以在同一页面上创建ajax.
In cookie.php put server side validation on form input.You can make ajax on same page also if you wanna put code on same page.
这篇关于通过PHP验证显示表单提交的数据值,而无需刷新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!