修复联系表单 - 已成功发送消息

时间:2017-07-21 11:24:46

标签: javascript php html forms contact-form

我在HTML中有一个着陆页,涉及通过联系表单发送数据。但是,如果您尝试使用联系表单,当您单击“提交”按钮时,将打开一个带有“成功”的新PHP页面。当我点击“提交”时没有打开页面,但是在“发送”按钮下面显示文本“消息已成功发送”,我该怎么办?

我无法解决这个问题。我应该在HTML和PHP中更改什么?

以下是我想要做的示例图片:

enter image description here

HTML CODE:

 <!-- Form -->
            <form class="contact-form" role="form" method="post" action="php/form-process.php">
              <i class="mdi-action-account-box"></i>

              <input type="text" class="form-control" name="name" placeholder="Nome" required="required">

              <i class="mdi-content-mail"></i>
              <input type="email" class="form-control" name="email" placeholder="Email"  required="required">

              <textarea class="form-control" name="message" placeholder="Messaggio" rows="4"  required="required"></textarea>

              <input type="checkbox" name="trattdati" required /> Accetto il trattamento dei miei dati ai sensi del D.Lgs. 196/03<br />
             <input type="checkbox" name="provasoftware" />  Desidero provare il software
<br /><br />
              <button type="submit" id="submit" class="btn btn-lg btn-primary" 
    style="float:left">Invia</button>

    <div id="success" class="success" style="    color: #009688;
    font-size: 20px;
    margin-top: -16px;
    float: left;
    margin-left: 25px;">
              </div>
            </form>
    <script>
        $(document).ready(function() {
            // This command is used to initialize some elements and make them work properly
            $.material.init();
            var options = {
                    target:        '#success',   // target element(s) to be updated with server response
                    beforeSubmit:  showRequest,  // pre-submit callback
                    success:       showResponse  // post-submit callback

                    // other available options:
                    //url:       url         // override for form's 'action' attribute
                    //type:      type        // 'get' or 'post', override for form's 'method' attribute
                    //dataType:  null        // 'xml', 'script', or 'json' (expected server response type)
                    //clearForm: true        // clear all form fields after successful submit
                    //resetForm: true        // reset the form after successful submit

                    // $.ajax options can be used here too, for example:
                    //timeout:   3000
                };

         // pre-submit callback
            function showRequest(formData, jqForm, options) {
                return true;
            }

            // post-submit callback
            function showResponse(responseText, statusText, xhr, $form)  {
                $('.contact-form')[0].reset();
                $('.contact-form').trigger("reset");
            }

            // bind form using 'ajaxForm'
            $('.contact-form').ajaxForm(options);


        });
    </script>

PHP文件:

<?php

$errorMSG = "";

// NAME
if (empty($_POST["name"])) {
    $errorMSG = "Name is required ";
} else {
    $name = $_POST["name"];
}

// EMAIL
if (empty($_POST["email"])) {
    $errorMSG .= "Email is required ";
} else {
    $email = $_POST["email"];
}

// MSG SUBJECT
//if (empty($_POST["msg_subject"])) {
//    $errorMSG .= "Subject is required ";
//} else {
//    $msg_subject = $_POST["msg_subject"];
//}


// MESSAGE
if (empty($_POST["message"])) {
    $errorMSG .= "Message is required ";
} else {
    $message = $_POST["message"];
}


$EmailTo = "bagiacchimarco7@gmail.com";
$Subject = "New Message Received";

// prepare email body text
$Body = "";
$Body .= "Name: ";
$Body .= $name;
$Body .= "\n";
$Body .= "Email: ";
$Body .= $email;
$Body .= "\n";
//$Body .= "Subject: ";
//$Body .= $msg_subject;
//$Body .= "\n";
$Body .= "Message: ";
$Body .= $message;
$Body .= "\n";

// send email
$success = mail($EmailTo, $Subject, $Body, "From:".$email);

// redirect to success page
if ($success && $errorMSG == ""){
   echo "success";
}else{
    if($errorMSG == ""){
        echo "Something went wrong :(";
    } else {
        echo $errorMSG;
    }
}

?>

3 个答案:

答案 0 :(得分:1)

假设您正在使用Javascript,根据您使用的任何插件的文档,您应该能够简单地执行:

function showResponse(responseText, statusText, xhr, $form)  {
    $('#success').html(responseText);
    $('.contact-form')[0].reset();
    $('.contact-form').trigger("reset");
}

同样,我做了一些假设,但responseText应该包含PHP页面中的数据。 #success看起来像div您想要表单反馈,html jQuery函数允许您将responseText放入#success div。

当然,其他答案都显示了在没有插件的情况下执行此操作的方法,但看起来您使用的是jQuery插件。

修改

阅读插件上的文档后,我想您可能只需要添加:

$('.contact-form').submit(function() { 
    // submit the form 
    $(this).ajaxSubmit(); 
    // return false to prevent normal browser submit and page navigation 
    return false; 
});

您需要仔细阅读有关您正在使用的所有插件的文档。

EDIT2

尝试将Raj的代码更改为

$('#submit').click(function(e){
    e.preventDefault() //Prevent the default action of the form.
    $.post( //Send a POST request to the PHP file via AJAX
        "php/form-process.php", //Path to the PHP file where you want to send the POST
         $(.contact-form).serializeArray().reduce(function(obj, item) {
             obj[item.name] = item.value;
             return obj;
         }, {}), // This takes all the form fields and returns key-value pairs of form data
    function (data) { //data = response from the PHP file. In your case "Sucess"
        if(data==="success"){
                //do something with data. Have assumed you want to append it to a div called "response". You will need to add <div id="success"> </div> below your form
            $('#success').html(data);
        } else {
            $('#success').html("Sorry Try Again"); 
        }
    });
)}

答案 1 :(得分:-2)

您可以使用点击提交按钮并填写所有内容然后重定向到success_page.php只需添加名称=&#34;提交&#34;它应该工作HTML:

更新2:工作示例---&gt;&gt; sample website(请注意错误,它只是一个简单的例子,您可以自己玩它。我将PHP添加到html文件中并且它可以正常工作。跳转这将对您有帮助。

更新:如果你想要它的include你的php页面应该打印出来。

&#13;
&#13;
<form class="contact-form" role="form" method="post" action="">
  <i class="mdi-action-account-box"></i>

  <input type="text" class="form-control" name="name" placeholder="Nome" required="required">

  <i class="mdi-content-mail"></i>
  <input type="email" class="form-control" name="email" placeholder="Email" required="required">

  <textarea class="form-control" name="message" placeholder="Messaggio" rows="4" required="required"></textarea>

  <input type="checkbox" name="trattdati" required /> Accetto il trattamento dei miei dati ai sensi del D.Lgs. 196/03<br />
  <input type="checkbox" name="provasoftware" /> Desidero provare il software
  <br /><br />
  <button type="submit" id="submit" class="btn btn-lg btn-primary" style="float:left">Invia</button>
  <?php
     
        $errorMSG = "";
        
        // NAME
        if (empty($_POST["name"])) {
            $errorMSG = "Name is required ";
        } else {
            $name = $_POST["name"];
        }
        
        // EMAIL
        if (empty($_POST["email"])) {
            $errorMSG .= "Email is required ";
        } else {
            $email = $_POST["email"];
        }
        
        // MSG SUBJECT
        //if (empty($_POST["msg_subject"])) {
        //    $errorMSG .= "Subject is required ";
        //} else {
        //    $msg_subject = $_POST["msg_subject"];
        //}
        
        
        // MESSAGE
        if (empty($_POST["message"])) {
            $errorMSG .= "Message is required ";
        } else {
            $message = $_POST["message"];
        }
        
        
        $EmailTo = "bagiacchimarco7@gmail.com";
        $Subject = "New Message Received";
        
        // prepare email body text
        $Body = "";
        $Body .= "Name: ";
        $Body .= $name;
        $Body .= "\n";
        $Body .= "Email: ";
        $Body .= $email;
        $Body .= "\n";
        //$Body .= "Subject: ";
        //$Body .= $msg_subject;
        //$Body .= "\n";
        $Body .= "Message: ";
        $Body .= $message;
        $Body .= "\n";
        
        // send email
        $success = mail($EmailTo, $Subject, $Body, "From:".$email);
        
        // redirect to success page
        if ($success && $errorMSG == ""){
           echo "success message sent!";
        }else{
            if($errorMSG == ""){
                echo "Something went wrong :(";
            } else {
                echo $errorMSG;
            }
        }
?>



    <div id="success" class="success" style="    color: #009688;
    font-size: 20px;
    margin-top: -16px;
    float: left;
    margin-left: 25px;">
    </div>
</form>
&#13;
&#13;
&#13;

答案 2 :(得分:-2)

您需要通过AJAX向您的PHP文件发送POST请求并处理DOM上的响应。

jQuery / AJAX代码

Customer3

另请查看validate.js。它处理前端本身的表单验证,并且还有一个非常好的方法来提交表单和管理响应。