2013-08-31 70 views
0

我正在嘗試使用Jquery和AJAX提交一個沒有頁面刷新的小型聯繫表單。我從另一個Stackoverflow線程獲得了代碼,但是當我嘗試提交表單並單擊提交按鈕時,什麼也沒有發生。我甚至在控制檯上也沒有收到任何錯誤消息。所以任何人都可以告訴我我在這裏做錯了什麼。這裏是形式通過AJAX提交表單無法正常工作

<form id="contactform" name="contactForm"> 
     <input type="text" name="name"/><br/> 
     <input type="text" name="email"/><br/> 
     <textarea name="comment"> 

     </textarea> 
     <p style='text-align:right;'><input type="submit"/></p> 
     </form> 

這裏是JS:

<script> 
// variable to hold request 
var request; 
// bind to the submit event of our form 
$("#contactform").submit(function(event){ 
    // abort any pending request 
    if (request) { 
     request.abort(); 
    } 
    // setup some local variables 
    var $form = $(this); 
    // let's select and cache all the fields 
    var $inputs = $form.find("input, select, button, textarea"); 
    // serialize the data in the form 
    var serializedData = $form.serialize(); 

    // let's disable the inputs for the duration of the ajax request 
    $inputs.prop("disabled", true); 

    // fire off the request to /form.php 
    request = $.ajax({ 
     url: "form.php", 
     type: "post", 
     data: serializedData 
    }); 

    // callback handler that will be called on success 
    request.done(function (response, textStatus, jqXHR){ 
     // log a message to the console 
     console.log("Hooray, it worked!"); 
    }); 

    // callback handler that will be called on failure 
    request.fail(function (jqXHR, textStatus, errorThrown){ 
     // log the error to the console 
     console.error(
      "The following error occured: "+ 
      textStatus, errorThrown 
     ); 
    }); 

    // callback handler that will be called regardless 
    // if the request failed or succeeded 
    request.always(function() { 
     // reenable the inputs 
     $inputs.prop("disabled", false); 
    }); 

    // prevent default posting of form 
    event.preventDefault(); 
}); 

</script> 

,並終於在這裏是post.php中的文件。

<?php 
echo $_POST['fullname']."<br/>"; 
echo $_POST['email']."<br/>"; 
echo $_POST['comment']."<br/>"; 

?> 

這裏是它的形式在頁面的網址:http://contestlancer.com/davidicus/

如果您在頭標誌點擊小信息圖標,你會看到聯繫表。

問候 艾哈邁爾

+0

好像你'form.php'不存在。 – putvande

+0

我剛剛調試了您的代碼,並且請求正在向您的螢火蟲控制檯發送錯誤消息 –

+0

Hi @SahilKapoor感謝您能否告訴我如何查看Firebug控制檯。對不起,如果它聽起來是一個愚蠢的問題 –

回答

5

你發送請求到form.php,你說你的文件名是post.php。更改此部分:

request = $.ajax({ 
     url: "form.php", 
     type: "post", 
     data: serializedData 
    }); 

要:

request = $.ajax({ 
     url: "post.php", 
     type: "post", 
     data: serializedData 
    });