-1

我想创建一个简单的电子邮件订阅表单,但还没有工作。这是我想做的步骤。

  1. 验证是使用 javascript 代码完成的,如果失败将弹出错误消息。
  2. 使用 AJAX 将输入传递到 MySQL 数据库并使用 PHP 脚本处理表单(服务器端)。
  3. 如果成功,.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>

代码有什么问题吗?

4

3 回答 3

0

大多数人不使用旧的 XMLHttpRequest,因为它依赖于浏览器。尝试使用 jQuery 等 javascript 框架。Ajax 调用最多 3 行。并尝试使用谷歌搜索 PHP jQuery Ajax。从长远来看,您的项目将更易于管理

于 2013-05-21T00:46:15.347 回答
0

我花了我从你的问题中删除了一些乱七八糟的代码行,才能为你工作。

<script type='text/javascript'>

    function subscribe(){
        var xmlhttp = false;

        if(window.XMLHttpRequest){
            xmlhttp = new XMLHttpRequest();
        }else{
            xmlhttp = ActiveXObject('Microsft.XMLHTTP');
        }


        xmlhttp.onreadystatechange  = function(){
           if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
                document.getElementById("ajaxanswer").innerHTML = xmlhttp.responseText;     
            }
        }

        var email  = document.getElementById("email").value;
        xmlhttp.open('GET', 'subscribe.php?email='+email, true);
        xmlhttp.send(null); // important for Firefox -3.0
    } 

</script>
    <input type="text" id="email" name="email">
    <input type="submit" onclick='subscribe()'  value="Submit Your Email">  
<div id="ajaxanswer"></div>

现在,您的 subscribe.php 文件应该包含以下 PHP 代码。

<?php

$email = $_GET['email'];
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
        echo 'invalid email';
    }else{
        echo 'your email is ok';
}
于 2013-05-21T00:48:54.587 回答
0

像这样在表单页面中使用 jquery 和 ajax

$('form id goes here).submit(function(e){
e.preventDefault();

var assign_variable_name_to_field = $("#field_id").val();
...

if(assign_variable_name_to_field =="")
{
handle error here
}

(don't forget to handle errors also in the server side with php)

after everyting is good then here comes ajax

datastring = $("form_id").serialize();

$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}

})

});

在 php 页面上

$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name

...

then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending 
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
于 2013-05-21T02:18:05.817 回答