提交表单后避免重新加载页面

时间:2013-04-02 02:32:33

标签: php jquery

您好我正试图通过电子邮件发送数据。我正在使用PHP mail()发送电子邮件和Ajax来提交数据以避免页面重新加载。我提交表单时没有发送电子邮件。我究竟做错了什么?代码有点像这样。

AJAX:

$('#submit').click(function(){

    $.ajax({
        url: test.php,
        type:'POST',
        success: function(msg){
                alert('Email Sent');
            }                   
        });
    });

HTML表单:

<table width="400" border="0" cellspacing="2" cellpadding="0"> 
   <tr> 
        <td>*Your name:</td> 
        <td><input name="name" type="text" id="name" size="32"></td> 
   </tr> 
   <tr> 
        <td class="bodytext">*Email address:</td> 
        <td><input name="email" type="text" id="email" size="32"></td> 
   </tr> 
   <tr> 
        <td class="bodytext"> </td> 
        <td align="left" valign="top"><input type="submit" name="Submit" id="submit" value="Send"></td> 
   </tr> 
</table> 

PHP:

<?php 
if ($_POST["email"]<>'') { 
    $ToEmail = 'somugus@gmail.com'; 
    $EmailSubject = 'Fusio Dose customer info'; 
    //$mailheader = "From: ".$_POST["email"]."\r\n"; 
    //$mailheader .= "Reply-To: ".$_POST["email"]."\r\n"; 
    //$mailheader .= "Content-type: text/html; charset=iso-8859-1\r\n"; 
    $MESSAGE_BODY = "Name: ".$_POST["name"]."\r\n"; 
    $MESSAGE_BODY .= "Email: ".$_POST["email"]."\r\n"; 
    $MESSAGE_BODY .= "Primary: ".$_POST["primary"]."\r\n";
    $MESSAGE_BODY .= "Sedcondary: ".$_POST["secondary"]."\r\n";
    //$MESSAGE_BODY .= "Comment: ".nl2br($_POST["comment"]).""; 
    mail($ToEmail, $EmailSubject, $MESSAGE_BODY, $mailheader) or die ("Failure"); 
?> 

工作示例在这里

http://soumghosh.com/otherProjects/Kemail/emailTest1.html

3 个答案:

答案 0 :(得分:2)

您可以序列化表单并将其提交到PHP页面。试试这个,它不会提交页面:

$('#contact_form').submit(function() {  
    alert($(this).serialize()); // check to show that all form data is being submitted
    $.post("test.php",$(this).serialize(),function(data){
        alert(data); //check to show that the email sent successfully                        
    });
    return false; // return false to stop the page submitting. You could have the form action set to the same PHP page so if people dont have JS on they can still use the form
});

答案 1 :(得分:0)

将您的函数调用更改为

$('#submit').submit(function(e) {

  e.preventDefault();
  //The rest of your code. 

   $.ajax({
    url: test.php,
    type:'POST',
    data: { name: $("#name").val(), email: $("#email").val() } // and so on
    success: function(msg){
            alert('Email Sent');
        }                   
    });
});



} 

答案 2 :(得分:0)

您实际上并没有通过AJAX请求传递表单中的值,只是发出“空”POST请求。您应该查看AJAX表单插件,它将为您做繁重的工作:

http://www.malsup.com/jquery/form/