gpt4 book ai didi

javascript - 将数据保存在数据库中而不在php中重定向

转载 作者:行者123 更新时间:2023-11-30 15:47:18 25 4
gpt4 key购买 nike

我有一个简单的表单,我想在不重定向的情况下将数据保存在我的数据库中。我正在为我的页面使用 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>

最佳答案

您在 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
}
});
}
});

Reference

关于javascript - 将数据保存在数据库中而不在php中重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39875327/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com