通过AJAX提交表单不起作用

艾玛·阿里(Ahmar Ali)

我正在尝试使用Jquery和AJAX提交小的联系表单,而无需刷新页面。我从另一个Stackoverflow线程获得了代码,但是当我尝试提交表单并单击“提交”按钮时,什么都没有发生。我什至在控制台上也没有收到任何错误消息。所以任何人都可以告诉我我在这里做错了什么。这是表格

 <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/>";

?>

这是具有以下格式的页面的URL:http : //contestlancer.com/davidicus/

如果单击标题徽标中的小消息图标,则会看到联系表。

问候阿马尔

撤消

您正在向发送请求,form.php并说您的文件名为post.php更改此部分:

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

到:

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章