我想创建一个简单的电子邮件订阅表单,但还没有工作。这是我想做的步骤。
- 验证是使用 javascript 代码完成的,如果失败将弹出错误消息。
- 使用 AJAX 将输入传递到 MySQL 数据库并使用 PHP 脚本处理表单(服务器端)。
- 如果成功,.responseText 将打印在文档对象上。
这是我的代码表单代码:
<div class="header_resize">
<div class="logo">
<h1><img src="images/logo.jpg" width="235" height="59" /></h1>
</div>
<div class="subs-form">
<p id="ajaxanswer"><b>Subscribe to our newsletter.</b></p>
<script>
<!--
function validateForm()
{
var x = document.forms["subscription"]["email"].value;
var atpos = x.indexOf("@");
var dotpos = x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
}
else
{
function ajaxFunction() {
var ajaxRequest; //The variable that makes AJAX possible!
try {
ajaxRequest = new XMLHttpRequest();
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert ("Your Browser is not compatible!");
return false;
}
}
}
// Function to receive data from server using XMLHttpRequest object property onreadystatechange
// onreadystatechange stores function to process response from server
ajaxRequest.onreadystatechange = function() {
// ajax.Request.readystate == 4 means the response is complete
if (ajaxRequest.readystate == 4) {
// response.Text is whatever data returned by server
document.getElementByID('ajaxanswer').value = ajaxRequest.reponseText;
}
}
var email = document.getElementById('email').value;
var queryString = "?email=" + email;
ajaxRequest.open("GET", "subscribe.php" + queryString, true);
ajaxRequest.send(null);
}
}
}
//-->
</script>
<form name="subscription">
<input type="text" name="email">
<input type="submit" onclick='validateForm()' value="Submit Your Email">
</form>
</div>
<div class="clr"></div>
</div>
这是我的php代码:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<?php
$conn=mysql_connect('localhost', 'dbuser', 'dbpwd') or die('Could not connect to MySql serve: ' . mysql_error());
mysql_select_db('dbname') or die('Could not select subscribe database: ' . mysql_error());
$safe_email = html_entity_decode($_GET['email']);
$sql="INSERT INTO subemail (email_addr) VALUES ('$safe_email')";
if (isset($_GET['email'])) {
$failure = "There was an error when submitting the form!";
$succeed = "Thank you for your subscription!";
$subject = "Message Form - Email Subscription.";
mail("my@email.com", $subject, "Email subscriber: " . $safe_email);
echo $succeed;
}
else {
echo $failure;
}
mysql_close($conn);
?>
</body>
</html>
代码有什么问题吗?