2014-02-15 109 views
1

我有我的网站发送电子邮件的联系表。我希望它在提交时不刷新页面,但要发送电子邮件和成功消息。我的表单就像我想提交我的联系人从没有页面刷新

<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> 
+0

您还没有在SO上搜索过。无论如何尝试这个https://stackoverflow.com/questions/1960240/jquery-ajax-submit-form/1960245#1960245 – anurupr

+0

可能重复[提交表单,而不提交按钮,没有页面刷新?](http:// stackoverflow。 com/questions/12386999/submit-a-form-without-submit-button-and-without-page-refresh) –

+0

你将不得不使用AJAX。具体来说,你需要做一个POST请求。看看这个答案:http://stackoverflow.com/a/1200312/1487730 – krisk

回答

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>