我目前正在尝试通过ajax将表单数据发送到php函数,但它似乎没有发送它。
这是HTML表单:
<form onSubmit="return registration();" id="registration_form">
<input type="email" id="email_address" name="email_address" class="inputTextFooter">
<input src="images/go.png" alt="Go" type="submit">
</form>
AJAX:
function registration(){
if(!$('#email_address').val()){
alert("Empty");
}
else {
$.ajax( {
type: "POST",
url: "includes/registration_check.php",
data: $('#registration_form').serialize(),
success: function( response ) {
alert( response );
}
});
}
return false;
};
最后是PHP:
$user_id = NULL;
$user_email = isset($_POST['email_address']) ? $_POST['email_address'] : '';
$distinct_query = "SELECT distinct user_email FROM user_emails";
$result=mysql_query($distinct_query, $connection);
$rows = mysql_num_rows($result) - 1;
$distinct_result_array = array();
while($fetched_array = mysql_fetch_assoc($result))
{
$distinct_result_array[] = $fetched_array;
}
for ($loop = 0; $loop <= $rows; $loop++) {
if (in_array($user_email, $distinct_result_array[$loop])) {
echo "Email taken.";
break;
}
else{
}
}
$query = "INSERT INTO user_emails (user_id, user_email) VALUES ('".$user_id."', '".$user_email."')";
mysql_query($query, $connection);
echo "You have successfully registered and will be checked by administration.";
当我发送表单时,它会添加到数据库,但电子邮件字段为空。
答案 0 :(得分:0)
替换
$user_email = isset($_POST['email_address']) ? $_POST['email_address'] : '';
使用
if(empty($_POST['email_address']))
{
echo "error";
exit;
}
else
{
$user_email = $_POST['email_address'];
}
我建议你使用mysqli而不是mysql,在插入数据库之前验证用户输入。
答案 1 :(得分:0)
您的函数应event.preventDefault()
限制默认表单提交操作
然后只有你的ajax请求被触发。
function registration(){
event.preventDefault();
if(!$('#email_address').val()){
alert("Empty");
}
else {
$.ajax( {
type: "POST",
url: "includes/registration_check.php",
data: $('#registration_form').serialize(),
success: function( response ) {
alert( response );
}
});
}
return false;
};
答案 2 :(得分:-2)
我认为您可能需要使用PHP的parse_str()函数来获取序列化数据