带有ajax错误消息的表单提交

时间:2014-01-29 05:57:18

标签: javascript php jquery ajax forms

我是ajax概念的新手。在这里,我试图将用户详细信息(注册表单)插入到数据库中。它成功地将数据插入到数据库中。但是,ajax是我的问题。

1)如果表单字段为空,我没有收到任何错误消息。您可以在post.php页面上看到我的以下代码。但是,它不会返回错误值。 2)它将空值存储到数据库中。 3)如果数据存储成功,我想获得成功消息&如果数据无法存储在db中我想获取错误消息。我应该怎么做这些事情?

Ajax.js

$(function () {
        $('form').on('submit', function (e) {
          $.ajax({
            type: 'POST',
            url: 'post.php',
            data: $('form').serialize(),
            success: function(msg) {
              if(msg=='error_n')
              {
                  $("#e_name").html('Name required');                    
              }
              if(msg=='error_m')
              {
                   $("#e_mobile").html('Mobile required');
              }

              //success and error alert
              if(data="inserted")
              {
                alert("insertion success");
              }
              else
              {
                alert("falid to insert into database");
              }
            }
          });
         e.preventDefault();
        });
      });

post.php中

<?php

    include_once('config.php');

    $name = trim($_POST["name"]);
    $mobile = trim($_POST["mobile"]);

    if($name == "")
    {
        echo 'error_n';
    }
    if($mobile == "")
    {
        echo 'error_m';
    }

    try
    {
        $stmt = $conn->prepare("INSERT INTO sample ( Name, Mobile ) VALUES ( ?, ? )");
        $conn->errorInfo();
        $stmt->bindParam('1', $name, PDO::PARAM_STR);
        $stmt->bindParam('2', $mobile, PDO::PARAM_STR);
        $stmt->execute();
    }
    catch(PDOException $e)
    {
        'Query failed to insert into database' .$e->getMEssage();
    }

?>

Homepage.php

<p>register <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a></p>

<div id="light" class="white_content">
  <a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>
   <form>
      <input type="hidden" name="form" value="values" />
      name : <input name="name" id="name" type="text" /><span id="e_name"></span> <br />
      mobile : <input name="mobile" id="mobile" type="text" /><span id="e_mobile"></span> <br />
      <input type="submit" value="submit" />
  </form>
</div>
<div id="fade" class="black_overlay"></div>

1 个答案:

答案 0 :(得分:2)

返回错误消息后,您需要停止脚本执行。您当前的代码仍尝试添加值,因此会覆盖您的自定义错误消息。很可能那么你的PHP会返回你的异常消息,这不是你期望的JavaScript。

if($name == "")
{
    echo 'error_n';
    die(); // Stop here
}
if($mobile == "")
{
    echo 'error_m';
    die(); // Stop here
}

在数据库插入成功时添加echo 'inserted';