运行PHP函数而不重新加载无法使用AJAX

时间:2017-06-05 22:08:21

标签: ajax

我知道这个问题已被问到很多,但我无法解决我的问题。 我想在不重新加载页面的情况下运行PHP函数。为什么这不起作用? php文件是indexTest.php。

页面只是滚动到顶部,没有任何效果。

我是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.
    }

?>

1 个答案:

答案 0 :(得分:0)

问题在于,当您真正想要通过AJAX发布时,您正在通过表单本身进行发布。基本上,因为您在onsubmit中调用JavaScript函数,JavaScript将在添加中运行到默认表单提交。

您需要做的是使用e.preventDefault();停用默认表单提交,然后运行JavaScript 而不是

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

希望这有帮助! :)