AJax不会提交到PHP表单

时间:2013-05-21 00:39:10

标签: php mysql ajax forms

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

  1. 验证是使用javascript代码完成的,如果失败则会提示弹出错误消息。
  2. 使用AJAX将输入传递到MySQL数据库并使用PHP脚本处理表单(服务器端)。
  3. 如果成功,.responseText将打印在文档对象上。
  4. 这是我的代码格式代码:

        <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>
    

    代码有什么问题吗?

3 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分: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';
}

答案 2 :(得分: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);
}