2017-06-05 51 views
0

我知道這個問題已經被問了很多,但我無法解決我的問題。 我想在不重新加載頁面的情況下運行PHP函數。爲什麼這不起作用? php文件是indexTest.php。運行PHP函數無需重新加載不會與AJAX一起工作

該頁面只是滾動到頂部,沒有任何工作。

我是AJAX的新手,所以我真的不知道該怎麼做。

HTML:

<script type="text/javascript"> 

     function submitdata() 
     { 
     var nameForm=document.getElementById("nameForm"); 
     var emailForm=document.getElementById("emailForm"); 
     var messageForm=document.getElementById("messageForm"); 

     $.ajax({ 
      type: 'post', 
      url: 'indexTest.php', 
      data: { 
      name:nameForm, 
      email:emailForm, 
      message:messageForm 
      }, 
     }); 

     return false; 
     } 
</script> 

<form onsubmit="return submitdata()" method="POST" id="contactForm"> 
        <input spellcheck="false" class="first" type="text" name="name" placeholder="name" id="nameForm"> 
        <input spellcheck="false" class="first" type="text" name="email" placeholder="email" id="emailForm"> 
        <textarea rows="8" spellcheck="false" class="last" type="text" name="message" placeholder="message" id="messageForm"></textarea> 
        <input type="submit" name="submit" value="" id="button">  
       </form> 

PHP:

<?php 
if(isset($_POST['submit'])){ 
    $to = "*"; // this is your Email address 
    $from = $_POST['email']; // this is the sender's Email address 

    if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { 
     echo "Invalid email format"; 
    }; 

    $first_name = $_POST['name']; 
    $subject = "Form submission"; 
    $subject2 = "Copy of your form submission"; 
    $message = "Email from: " . $from . "\n\n" . $first_name . " wrote the following:" . "\n\n" . $_POST['message']; 
    $message2 = "Here is a copy of your message " . $first_name . "\n\n" . $_POST['message']; 

    $headers = "From:" . $from; 
    $headers2 = "From:" . $to; 
    mail($to,$subject,$message,$headers); 
    mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender 

    echo '<script language="javascript">'; 
    echo 'alert("message successfully sent")'; 
    echo '</script>'; 

    // You can also use header('Location: thank_you.php'); to redirect to another page. 
    } 

?> 
+0

會發生什麼?你在控制檯中看到什麼? – SLaks

+0

您無法序列化DOM元素爲JSON。你可能想要得到它的價值。 – SLaks

+0

什麼也沒有發生,頁面只是滾動到頂部。首先,我使用了action =「indexTest.php」,但沒有使用AJAX,它工作。但它重新加載了頁面,我發現我必須使用AJAX。 – Soccerlife

回答

0

的問題是,你是通過形式本身,當你真正想通過AJAX張貼發佈。實質上,因爲您在onsubmit中調用您的JavaScript函數,JavaScript將運行另外默認的表單提交。

你需要做的是禁用默認表單提交與e.preventDefault();,然後運行你的JavaScript ,而不是

$("#contactForm").submit(function(e) { 
    e.preventDefault(); 
    submitdata(); 
}); 

希望這有助於! :)