首页 > 解决方案 > 重新加载页面(发送表单)

问题描述

我在重新加载页面时遇到问题。单击提交表单后,页面重新加载。我单击发送表单并将我带到 http://localhost:3000/mail.php。我希望该网站不要重新加载。(我使用验证表单 jquery 插件)。这是我的代码:jquery

  (function(){
    $("#contactForm").on('submit', function(e) {
          e.preventDefault();
          var data = {
            name = $('#field-name').val(),
            phone = $('#field-phone').val(),
            email = $('#field-email').val(),
            message = $('#field-message').val()
        };
        $.ajax({
            type: "POST",
            url: "mail.php",
            data: data,
            success: function(){
                console.log("jej");
            }
        });
        return false;
      });
  });

和php代码

<?php
    $to = 'name@gmail.com';
    $name = $_POST['name'];
    $phone = $_POST['phone'];
    $email= $_POST['email'];
    $text = $_POST['message'];
    $subject = 'Nowy e-mail od ' . $name . ' (' . $email . ')';
    $message =  $name  . $phone .  $email . $text;
    $headers = 'From: ' . $name . "\r\n" .
    if(mail($to, $subject, $message, $headers)) {
      print "<p class='success'>Mail Sent.</p>";
    } else {
        print "<p class='Error'>Problem in Sending Mail.</p>";
    }

?>

标签: phpjqueryajax

解决方案


更改部分代码

$("#contactForm").on('submit', function(e) 

对这个……

$("#contactFormButton").on('click', function(e) 

并将您的提交按钮更改为此...

<button id="contactFormButton" type="button" class="form-control">Submit</button>

在这里你的php代码......

if(mail($to, $subject, $message, $headers)) {
      echo "Mail Sent!";
    } else {
        echo "Error!!";
    }

在这里你可以捕捉到你的 php 代码的结果......

        success: function(data){
            console.log(data);
        }

推荐阅读