簡體   English   中英

提交表單后避免重新加載頁面

[英]avoiding page from reloading after submitting the form

嗨,我試圖從數據發送電子郵件。 我正在使用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

您可以序列化表單並將其提交到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
});

將您的函數調用更改為此

$('#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');
        }                   
    });
});



} 

您實際上並沒有在表單中傳遞值,而只是在AJAX請求中傳遞“空”POST請求。 你應該看看AJAX表單插件,它將為你做繁重的工作:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM