【问题标题】:AJax won't submit into PHP form [closed]AJax 不会提交到 PHP 表单中[关闭]
【发布时间】:2013-05-21 00:39:10
【问题描述】:

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

  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>

代码有什么问题吗?

【问题讨论】:

  • 不询问 specific problem 的问题不适合 Stack Overflow。具体来说,如果一个问题是以引发讨论的方式提出的,或者总体上是主观的,它should not be asked here。如果你有问题,消除它们并询问它们,但只是扔掉很多代码,附有“这是很酷的代码吗?”不属于这里。
  • id ajaxanswer 在哪里?因为你在这里叫它document.getElementByID('ajaxanswer').
  • PHP 代码中不需要所有的 html 标签
  • @hanjaya 检查我的答案,几乎所有代码都放错了位置,并且有大小写问题
  • 在你深入学习 mysql 之前...... mysql_* 函数非常陈旧、不安全,并且很快就会从 PHP 中删除(据我所知),请尝试阅读PDOMySQLi.

标签: php mysql ajax forms


【解决方案1】:

我花了我从您的问题中删除一些乱码的代码行,以使其适合您。

<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';
}

【讨论】:

  • 嗨 php NoOb,感谢您的回复。我明天会在我的工作场所检查这个。
  • 在客户端还是服务器端验证输入更好?
  • @hanjaya 没关系,因为在 subscribe.php 上你应该获取值,并验证它,而且由于你使用的是 Ajax,所以页面不会刷新,所以没有区别,事实上,最好是定制化 php 页面而不是弹出 javascript 框。如果你想让我添加一个简单的 php 验证,我会告诉你。
  • @hanjaya 顺便说一句,如果这个回答对你有帮助,别忘了接受它:)
  • 如果你不介意的话,你也可以发布 php 验证。我刚刚做了,但没有成功。
【解决方案2】:

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

【讨论】:

    【解决方案3】:

    像这样在表单页面中使用 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);
    }
    

    【讨论】:

      猜你喜欢
      • 2015-10-08
      • 2014-02-14
      • 1970-01-01
      • 2013-03-07
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多