gpt4 book ai didi

php - 如果表单为空则不提交表单

转载 作者:搜寻专家 更新时间:2023-10-31 21:37:01 25 4
gpt4 key购买 nike

这是我的第一篇文章,我是 php + ajax 的新手。

我的大部分编码设置现在唯一的问题是,当我按下提交按钮时,会出现一个通知,该通知只应在文本字段不为空时显示。

这是我的代码:

<head><script> 
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
alert("Thank you for subscribing to SHCA");
document.forms["ContactForm"].reset();
});
});

</script> </head>

接着是一些 php 编码:

<?php
if(strlen($_POST['name']) > 0 AND strlen($_POST['email']) > 0)
{
if(isset($_POST['submit']))
{
$hostdb = '';
$namedb = '';
$userdb = '';
$passdb = '';

$conn = mysqli_connect($hostdb , $userdb, $passdb ,$namedb);


$sql = "INSERT INTO subscribers (name, email) VALUES('$_POST[name]', '$_POST[email]')";



if (!mysqli_query($conn, $sql))
{
die('Error: ' .mysql_error($conn));
}

if (!mysqli_ping($conn)) {
echo 'Lost connection, exiting after query #1';
exit;
}

mysqli_close($conn);
}}
else
{

?>

        <form id="ContactForm" action="" method="post">

<label for="author">Name:</label> <input type="text" id="name" name="name" class="required input_field float_r" />
</br>
</br>
<label for="email">Email:</label> <input type="text" id="email" name="email" class="validate-email required input_field float_r" />

<div class="cleaner h10"></div>

<input type="submit" value="Subscribe" id="submit" name="submit" class="submit_btn float_l" />
</form>
<?php } ?>

希望这里的任何人都能够告诉我我应该怎么做才能在文本字段不为空时只显示“感谢您订阅 SHCA”消息

最终回答者 Dereck 忘记了对象中的 '' 所以大声喊叫 dereck 帮助我!

$(document).ready(function() { 
// bind 'myForm' and provide a simple callback function
$('#ContactForm').ajaxForm(function() {
if( !$('#name').val()) {
alert("please enter your name");
}
if(!$('#email').val()) {
alert("plese enter your email adress");
}
else{
alert("Thank you for subscribing to SHCA");
}

document.forms["ContactForm"].reset();
});
});

最佳答案

在提交给服务器之前需要检查字段的内容,一个简单的脚本方法可以在提交之前进行检查。如果字段为空,则显示错误消息并且不提交表单。

function SubmitDetails()
{
if(window.ContactForm.name.value == "")
{
window.alert("Please enter a name");
return;
}if(window.ContactForm.email.value == "")
{
window.alert("Please enter an email" );
return;
}

window.ContactForm.submit();
}

关于php - 如果表单为空则不提交表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16751387/

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