Ajax阻止表单操作和发布表单数据

时间:2013-08-09 02:12:07

标签: php ajax forms jquery post

我一直在搜索示例,试图解决我的简单电子邮件注册表单。我试图只是向数据库提交电子邮件,而无需离开或重新加载当前页面。我能够将新数据插入我的数据库,但不能通过我的Ajax函数。我开始认为我的Ajax函数没有被调用,因为即使使用event.preventDefault();函数,我的页面也会被重定向到.php文件。我在下面列出了我的脚本,该脚本目前位于我的HTML的<head></head>部分。

<script type="text/javascript">
$(document).ready(Function() {
    $("#submitbtn").click(function(event) {

            event.preventDefault();

        var form = $(this),  
            emailcode = form.serialize(),
            formUrl = form.attr('action'),
            formMethod = form.attr('method');
            /* responseMsg = $('#signup-response') */

            if ( formData.length===0 ) {

            function(msg){
            alert('Invalid Email');
            }
            return false;
            } else {

            //send data to server  
            $.ajax({  
                url: formUrl,
                type: formMethod,
                data: emailcode,
                success:function(data){
                alert('Email Saved');
        } 

        return false;
          });
      };
   });
});

HTML

<form class="col-lg-5 form-group pull-right well" id="emailform" action="collector.php" method="POST" style="padding-top:6px;">
      <label for="email-input">Sign up to receive updates</label>
      <input type="email" class="form-control" id="emailcode" placeholder="Email" name="emaildata" autofocus></input>
      <button type="submit" id="submitbtn" class="btn btn-success" style="width:60%">Sign Up</button>
      </form>

PHP     

    $emailcode = $_POST['emailcode'];

            //Fetching from your database table.
            $query = "INSERT INTO EmailCollector (EmailID, EmailCode, Active)
            VALUES (NULL,'$emailcode', 0)";
            $result = mysql_query($query);

    mysql_close();

?>

1 个答案:

答案 0 :(得分:1)

我注意到了一个快速的事情。

form = $(this)  //it is holding submit button, not the form
emailcode = form.serialize(),
formUrl = form.attr('action'), //there is no attribute `action` to select because form is holding submit button
formMethod = form.attr('method'); //similarly, there is no attribute method

将表单选择器更改为:

form = $('#emailForm')