簡體   English   中英

Ajax阻止表單操作並發布表單數據

[英]Ajax prevent form action and post form data

幾天來我一直在搜索示例,以嘗試對我的簡單電子郵件注冊表單進行故障排除。 我正在嘗試只向數據庫提交電子郵件,而不會離開或重新加載當前頁面。 我可以將新數據插入數據庫, 但不能通過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();

?>

我注意到一個快速的事情。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM