我使用php,Ajax和amp;为我的网站制作了一个表单jQuery的。当我第一次提交带有一些输入的表单时它工作正常,但第二次没有重新加载页面它显示错误。使用类id和类型attr时,html输入标签很简单。
我想要的是如果用户提交表单,代码也会第二次运行。
php和jquery:
if(isset($_POST['submit'])){
$name = $_POST['name'];
$website = $_POST['website'];
// $category = $_POST['category'];
$toscheckbox = $_POST['toscheckbox'];
$errorEmpty = false;
$website_error = false;
$name_error = false;
$toscheckbox_error = false;
if(empty($name) || empty($website) || empty($toscheckbox)){
echo "<span class='alert alert-danger' role='alert'>Please fill in all fields!</span>";
$errorEmpty = true;
}
elseif (!filter_var($website, FILTER_VALIDATE_URL)){
echo "<span class='alert alert-danger' role='alert'>Write a valid URL!</span>";
$website_error = true;
}
elseif (!preg_match("/^[a-zA-Z0-9][a-zA-Z0-9 \t]*$/", $name)) {
echo "<span class='alert alert-danger' role='alert'>Please check your Website Name</span>";
$name_error = true;
}
else {
echo "<span class='alert alert-success'>Thanks your submission listed in our Database!</span>";
}
}
else {
echo "<span class='alert alert-danger'>There was something wrong with your form</span>";
}
<script>
// $("#name, #website, #toscheckbox").removeClass("border border-danger");
var errorEmpty = "<?php echo $errorEmpty; ?>";
var website_error = "<?php echo $website_error; ?>";
var name_error = "<?php echo $name_error; ?>";
var toscheckbox_error = "<?php echo $toscheckbox_error; ?>";
if(errorEmpty == true){
$("#name, #website, #toscheckbox").addClass("border border-danger");
}
if(website_error == true) {
$("#website").addClass("border border-danger");
}
if(name_error == true) {
$("#name").addClass("border border-danger");
}
if (errorEmpty == false && name_error == false && website_error == false && toscheckbox_error == false) {
$("#name, #website, #toscheckbox").val("");
}
</script>
<script>
$(document).ready(function() {
$("form").submit(function(event){
event.preventDefault();
var name = $("#name").val();
var website = $("#website").val();
var toscheckbox = $("#toscheckbox").val();
var submit = $("#submit").val();
$(".text-danger").load("ajaxreturn.php", {
name: name,
website: website,
toscheckbox: toscheckbox,
submit: submit
});
});
});
</script>
编辑HTML:
<input class="form-control" id="name" type="text" name="name">
<input name="toscheckbox" class="form-check-input" id="toscheckbox" type="checkbox" value="ToS">
<input class="form-control form-control" id="website" type="text" name="website">