我在模态中有一个表单,我想在提交表单后阻止模式关闭和刷新页面如果某些字段有错误并在模态内显示错误消息,如果一切正常,模态应该提交形成并刷新页面。
这是我的代码:
<div class="modal fade" id="addTeam">
<div class="modal-dialog rap-modal-thumb">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">X</span></button>
<h4 class="modal-title" id="myModalLabel">Add team</h4>
</div>
<div class="modal-body"><br>
<div class="page-wrap">
<form action= "<?php echo $action; ?>" enctype="multipart/form-data" method="post">
<div class="container">
<div class="row">
<div class="input-group input-group-icon">
<div class="col-third input-group-icon">
<input type="text" id="name" name="name" placeholder="Nom*" required="required">
<div class="input-icon"><i class="fa fa-users"></i></div>
</div>
<div class="col-third input-group-icon">
<input type="text" id="abreviation" name="abreviation" placeholder="Abréviation*" required="required">
<div class="input-icon"><i class="fa fa-flag-o"></i></div>
</div>
<br>
* Required fields
<br><br>
<?php
if (isset($error))
echo '<div style="color:#fff;" class="alert bg-danger" role="alert"><em class="fa fa-lg fa-warning"> </em>',$erreur,'</div>';
?>
<button type="submit" id="addTeam" name="addTeam" class="btn btn-primary">Ajouter</button>
</div>
</form>
</div>
<br>
</div>
</div>
</div>
在php中,例如团队名称少于6个字符,然后在模态中显示错误消息而不关闭它。在我的情况下,在刷新页面并再次单击模态的显示按钮后,将显示该消息。
if (isset($_POST['addTeam'])) {
$name= $_POST['name'];
if (strlen($name)<3){
$error = 'Name must be atleast 6 characters';
}
else{
$action = "uploadTeam.php";
}
}
无论如何要做到这一点?
答案 0 :(得分:3)
如果您的表单默认由浏览器提交,它将自动刷新页面(以向服务器创建新的HTTP POST请求)
您必须使用AJAX在后台调用服务器,并避免重新加载内容:
// Create an event listener to catch "when the form is submited"
$('.modal-body form').submit(function(event) {
// to stop the form from submitting (and the page reloading, so the modal will not close)
event.preventDefault();
// Call server manually and send form data (see Mikey's comment)
$.post('my.url.com/file.php', $(this).serialize(), function(err, result) {
if (err) {
// Display error on form
} else {
// Success... Redirect ?
window.location = 'my.new.url/path.html'
}
})
});
答案 1 :(得分:1)
您需要为此覆盖一些客户端行为。事实上,您可以更轻松地在客户端进行验证(如果可能)。覆盖表单的默认行为,验证,然后根据验证函数的结果返回true
或false
:
<script>
$('form').on('submit', function(e) {
if (validate()) { //your validation function here
return true;
}
return false;
});
function validate() {
if (!$('input[name=name]').val() || $('input[name=name]').val().length < 3) {
return false;
}
return true;
}
</script>