我想在没有页面刷新的情况下提交我的联系方式

时间:2014-02-15 08:57:29

标签: javascript jquery html css forms

我的网站上有一个发送电子邮件的联系表格。我希望它不会在提交时刷新页面,但会发送电子邮件和成功消息。我的表格就像

<form method="post" id="contactform" enctype="multipart/form-data">
<input class="contactusfeild" style="width:222px;" name="sendername"  type="text" placeholder="Your Name" required>
<input class="contactusfeild" name="senderemail" style="width:222px;"  type="email" placeholder="Your Email" required >
<textarea name="sendermessage" class="contactusfeild" type="text" placeholder="Your Message Here" style="width:220px; max-width:220px; height:100px; max-height:100px; padding-top:10px;" required ></textarea>
<input  class="button"  style="border:none;" type="reset"  value="Clear" /><input  name="contactcozmuler" class="button" style="border:none; margin " type="submit"  id="submit_btn" value="Send" />
</form>

2 个答案:

答案 0 :(得分:0)

使用ajax帖子。查看example和jQuery文档:.post().ajax()

答案 1 :(得分:0)

首先要做的事情。

您无法使用ajax上传文件,但是如果您将使用第三方脚本。

您可以使用jQuery轻松提交没有刷新页面的表单。

我写这个例子是为了清楚谁搜索这个问题。

如果你想要所有表单都使用ajax提交,那么你只能将'form'标签定义为jquery选择器。

<script type="text/javascript">

//Call Document load
$(function(){

    // Find form elements to use ajax with
    $targetForms = $('form.ajax'); // In here, we are selecting forms that only has ajax class

    // By using submit function, you can use html5 required validation.
    // If you want to on click with buttons, html5 validation will not work.
    $targetForms.submit(function(){
        var $this = $(this); // This is now your form element.

        $.ajax({
            url: $this.attr("action"), //Where do you want to make request?
            type: $this.attr("method"), //Which method will use for request POST or GET?
            dataType: "html",
            data: $this.serialize(), // Collect all form data
            beforeSend: function(){
                // You can define what will happen just when before request.
            },
            success: function(response){,
                /* Lets think here what we can return and which type data will be. 
                   For example if you will return a string and then dataType must be choose HTML. 
                   If message successfully sent to email or recorded to db, you can send here a string like "sent". 
                   Or if error occures, you can send here a string like "error". We will use this strings in this example.
                */

                if(response == "sent") {
                    // Animate your form to height:0 and show a div that have message for visitor.

                } else if(response == "error")) {
                    alert("Hey! Something bad happened!");
                }
            },
            error: function(){

            }
        });

        return false;
    });
});
</script>