表单成功处理后如何执行操作?

时间:2017-03-07 20:07:04

标签: javascript php jquery ajax forms

我想让表单隐藏,并在表单成功提交后显示感谢信息而不是它。我已经完成了以下代码,但是在提交表单后我无法完成任何操作...就像'if'函数被忽略一样。

以下是我的代码:

JQuery的:

$('form#contactform').submit(function(event) {

var formData = {

    //get form data
    'name' : $('input[name=name]').val(),
    'email' : $('input[name=email]').val(),
    'subject' : $('input[name=subject]').val(),
    'message' : $("#msg").val(),

};

$.ajax({
    type : 'POST',
    url : 'sendmail.php',
    data : formData,
    dataType : 'json',
    encode : true   
})

//Done promise callback
.done(function(data) {

    //log data to console
    console.log(data);

    //Errors and validation messages        
    if (! data.success == true) {

        $('section#contact form#contactform').hide;
        $('section#contact div.thxform').show;

    } else {

        alert("An internal error has occured");

    }

});

//Stop form default action
event.preventDefault();

腓:

<?php

$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data

//validate variables
if (empty($_POST['name']))
    $errors['name'] = 'Name is required';

if (empty($_POST['email']))
    $errors['email'] = 'E-Mail is required';

if (empty($_POST['subject']))
    $errors['subject'] = 'Subject is required';

if (empty($_POST['message']))
    $errors['message'] = 'Please enter a message';

//Return response
if ( ! empty($errors)) {          //If there are errors

    $data['success'] = false;
    $data['errors'] = $errors;

} else {

    //Process form
    $name = $_POST['name'];
    $email = $_POST['email'];
    $re = $_POST['subject'];
    $message = $_POST['message'];

    $from = 'info@jamescremona.com';
    $to = 'jmscre@gmail.com';
    $subject = 'Form submission';

    $body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";

    if (mail ($to, $subject, $body, $from)) { 
        echo '<p>Your message has been sent!</p>';
    } else { 
        echo '<p>Something went wrong, go back and try again!</p>'; 
    }       

    $data['success'] = true;
    $data['message'] = 'Form Submitted';

}

echo json_encode($data);

非常感谢任何帮助。感谢。

4 个答案:

答案 0 :(得分:1)

我发现您的代码出现了第一个错误:

'message' : $("#msg").val(),这是您阵列中的最后一项,因此不需要&#39;,&#39; javascript期待&#39;,&#39;

之后的更多项目

您需要在控制台中检查所有js错误,它们就在那里。

然后是我看到的第二个错误,

$('section#contact form#contactform').hide; $('section#contact div.thxform').show; 他们有show();hide();在jquery中不存在显示和隐藏,然后在这里:if (! data.success == true) {}

这是您的代码的外观:

<script type="text/javascript">
$('form#contactform').submit(function(event) {

var formData = {

    //get form data
    'name' : $('input[name=name]').val(),
    'email' : $('input[name=email]').val(),
    'subject' : $('input[name=subject]').val(),
    'message' : $("#msg").val()

};

$.ajax({
    type : 'POST',
    url : 'sendmail.php',
    data : formData,
    dataType : 'json',
    encode : true   
})
.done(function(data) {
    //log data to console
    console.log(data);

    //Errors and validation messages        
    if (!data.success) {

        $('section#contact form#contactform').hide();
        $('section#contact div.thxform').show();

        //check which field was wrong and show the user
        if(data.errors.name){

            $('section#contact div.thxform').append(data.errors.name);
        }
        if(data.errors.email){

           $('section#contact div.thxform').append(data.errors.email); 
        }
        if(data.errors.subject){
            $('section#contact div.thxform').append(data.errors.subject);
        }
        if(data.errors.message){
            $('section#contact div.thxform').append(data.errors.message);
        }

    }else{

        $('#successDIV').append(data.message);
    }

}),
.fail(function(data){
    //debugging puporses, all your php errors will be printed in the console
    console.log(data);

});

//Stop form default action
event.preventDefault();
</script>

答案 1 :(得分:0)

您需要告诉浏览器预期的内容。所以在echo之前添加header函数

header('Content-Type: application/json'); // this line here
echo json_encode($data);

<强>更新

你的event.preventDefault();最后一个应该是你在$(&#39;形式#contactform&#39;)之后调用的第一件事.admit(function(event){因为你想在ajax调用之前阻止它。

另外,PHP在邮件函数返回值的任何一种情况下都会回显东西。所以json响应搞砸了,因此你的ajax将无法获得正确的数据。

更新2

我强烈感觉你的PHP脚本会抛出某种错误。例如,邮件功能可能会抛出530错误。因此,最好禁用PHP脚本中的错误显示。 调试的一般建议这类内容是web developer browser extensions来查看请求/响应信息。

请尝试使用此重构代码:

ini_set('display_errors',0); // disable error displaying. Rather view in logs
$errors = array(); //array to hold validation errors
$data = array(); //array to pass back data

//validate variables
if (empty($_POST['name']))
    $errors['name'] = 'Name is required';

if (empty($_POST['email']))
    $errors['email'] = 'E-Mail is required';

if (empty($_POST['subject']))
    $errors['subject'] = 'Subject is required';

if (empty($_POST['message']))
    $errors['message'] = 'Please enter a message';

//Return response
if ( ! empty($errors)) {          //If there are errors

    $data['errors'] = $errors; // only necessary to set errors

} else {

    //Process form
    $name = $_POST['name'];
    $email = $_POST['email'];
    $re = $_POST['subject'];
    $message = $_POST['message'];

    $from = 'info@jamescremona.com';
    $to = 'jmscre@gmail.com';
    $subject = 'Form submission';

    $body = "From: $name\n E-mail: $email\n Subject: $re\n Message: $message\n";

    if (mail ($to, $subject, $body, $from)) {
        $data['success'] = 'Your message has been sent!'; // store to $data instead of echo out
    } else {
        $data['errors'] = 'Something went wrong, go back and try again!'; // store to $data instead of echo out
    }

}

header('Content-Type: application/json');
echo json_encode($data);

你在ajax调用的done函数中的javascript片段:

    <script type="text/javascript">
    $('#contactform').submit(function(event) {

        event.preventDefault(); // note this one has to be at the beginning of your submit function since you do not want to submit

        var formData = {

            //get form data
            'name' : $('input[name=name]').val(),
            'email' : $('input[name=email]').val(),
            'subject' : $('input[name=subject]').val(),
            'message' : $("#msg").val(),

        };

        $.ajax({
                type : 'POST',
                url : 'sendmail.php',
                data : formData,
                dataType : 'json',
                encode : true
            })

            //Done promise callback
            .done(function(data) {

                //log data to console
                console.log(data);

                //Errors and validation messages
                if (data.success) { // success either exists or not

                    alert("Success! Form should hide now...");

                    $('#contactform').hide(); // an id is (should always) be unique. So you dont need this "section#contact form#contactform". It does not make sense. Also hide and show are functions and need brackets at the end
                    $('div.thxform').show();

                } else { // then its an error

                    alert("An internal error has occured");

                }

            });

    });
</script>

用于测试的HTML:

<form method="post" id="contactform">
Name <input type="text" name="name" value="test"><br>
Email <input type="text" name="email" value="test@localhost.com" ><br>
Subject <input type="text" name="subject" value="subject" ><br>
Message <textarea name="message" ></textarea><br>
<input type="submit">
</form>

答案 2 :(得分:0)

因为两个小错误:

  1. [js code]将if (! data.success == true)替换为if (data.success == true)
  2. [php code]在header('Content-Type: application/json'); echo
  3. 之前添加$data

答案 3 :(得分:0)

我猜问题就在这里

if (mail ($to, $subject, $body, $from)) { 
    echo '<p>Your message has been sent!</p>';
} else { 
    echo '<p>Something went wrong, go back and try again!</p>'; 
} 

因为你echo是一个字符串,然后是一个json对象。因此,当您对Javascript处理data响应时,它不是json对象。

然后我会在PHP中执行以下操作

if (@mail($to, $subject, $body, $from)) { 
    $data['success'] = true;
    $data['message'] = 'Form Submitted';
} else { 
    $data['success'] = false;
    $data['message'] = 'Internal error';
} 
echo json_encode($data);

并在Javascript中

.done(function(data) {
    if (typeof data !== 'object') {
            alert('Expected data as object - '+typeof data+' received');
            return;
    }
    data = jQuery.parseJSON(data);

    //Errors and validation messages        
    if (data.success == true) {
        $('section#contact form#contactform').hide;
        $('section#contact div.thxform').show;
    } else {
        alert(data.message);
    }

});

请注意,@函数之前的mail operator不会生成错误消息,以避免在Javascript上发送字符串。

相关问题