我有一个简单的表单,我想在没有重定向的情况下将数据保存在我的数据库中。我正在为我的页面使用php,ajax和jquery。我不知道我是否做错了但是在点击提交按钮后,表单数据出现在地址栏上。数据成功存储在数据库中,但页面也重新加载。我的代码如下。
HTML
<form>
<input type="text" placeholder="Full Name*" required pattern= "[a-zA-Z]+" title="Alphabets only" name="name" id="name">
<input type="email" placeholder="Email*" required pattern="[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$" name="email" id="email">
<input type="text" placeholder="Contact*" required pattern="[0-9]\d{9}" title="only 10 digit allowed" name="contact" id="contact">
<textarea placeholder="Enquiry(if any)" name="msg" id="msg"></textarea>
<button type="submit" name="register" id="register_btn">Register</button>
<span id="success"></span>
<span id="error"></span>
</form>
PHP
include("conn/connect.php");
if(isset($_POST['email'])){
$email= mysqli_real_escape_string($connect, $_POST['email']);
$name= mysqli_real_escape_string($connect, $_POST['name']);
$contact= mysqli_real_escape_string($connect, $_POST['contact']);
$msg= mysqli_real_escape_string($connect, $_POST['msg']);
$sql= "INSERT INTO registration(email, name, contact, msg, added_on) values('$email','$name','$contact','$msg', now())";
if(mysqli_query($connect, $sql))
{
echo '<h4>Registration Complete</h4>';
}
}
JAVASCRIPT
<script>
$(document).ready(function(){
$('#register_btn').click(function(){
var name = $('#name').val();
var email = $('#email').val();
var contact = $('#contact').val();
var msg = $('#msg').val();
if(name == '' || email == '' || contact == '')
{
$('#error').html("<h4>Mandatory field(s) are empty</h4>");
setTimeout(function(){
$('#error').fadeOut("Slow");
}, 3000);
}
else
{
$('#error').html('');
$.ajax({
url:"registration.php",
type:"POST",
data:{name:name, email:email, contact:contact, msg:msg},
success:function(data){
$("form").trigger("reset");
$('#success').fadeIn().html(data);
setTimeout(function(){
$('#success').fadeOut("Slow");
}, 3000);
}
});
}
});
});
</script>
答案 0 :(得分:2)
您正在submit
按钮上调用一个将刷新页面的活动。
在点击功能中使用event.preventDefault()
。
$(document).ready(function(){
$('#register_btn').click(function(event){
event.preventDefault();
});
});
仅供参考,如果您的验证停止工作,请尝试执行此操作。
$('#register_btn').click(function(event) {
//Check form is valid
if ($(this).closest('form')[0].checkValidity()) {
// stop form from redirecting to java servlet page
event.preventDefault();
$.ajax({
type: form.attr("method"), // use method specified in form attributes
url: form.attr("action"), // use action specified in form attributes
data: form.serialize(), // encodes set of form elements as string for submission
success: function(data) {
// get response from servlet and display on page via jQuery
}
});
}
});
答案 1 :(得分:0)
正在加载..指出您需要事件阻止默认但在表单提交事件中,如下所示:
$('form').on('submit', function(e){
return false;
});
在submit = e.preventDefault + e.sotpPropagation
上返回false