我已成功使用ajax通过ajax在线刷新联系表单。我正在使用发送到mysql的数据时遇到更多困难。我很欣赏我到目前为止所做的并不打算通过ajax刷新,所以它可能需要一些工作。这就是我所得到的......任何帮助都表示赞赏。
表格
<form name="email_list" action="">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" name="submit" value="Submit Form" class="email_submit"></p>
</form>
JQuery的
$(function() {
$('.email_submit').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = $(this).serialize();
//alert (dataString);return false;
/*$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});*/
});
PHP
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["action"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// add record
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address - ".$_POST["email"]." - is already subscribed.";
}
}
}
?>
<html>
<?php echo "$display_block";?>
</html>
**进行更改后更新如上:)
答案 0 :(得分:1)
有一些问题,例如:
您需要将javascript附加到事件(表单提交),因此第一部分将是:
$('form').submit(function() {
您需要发送所有(正确的...)表单值,而不仅仅是您的php工作的电子邮件地址:
$('form').submit(function() {
var dataString = $(this).serialize();
答案 1 :(得分:0)
您错过了服务器中的数据(删除服务器中的HTML标记):
$.ajax({
type: "POST",
url: "mailing_list_add.php",
data: dataString,
success: function(data) {
$('#email_add').html("<div id='response'></div>");
$('#response').html("<h2>Successfully added to the database.")
.hide()
.fadeIn(2500, function() {
$('#response').html(data);
});
}
});