我的ajax php表单不起作用

时间:2016-09-06 04:16:49

标签: php ajax contact-form

大家好!我的网页中有一个包含我的联系表格

<?php include 'footer.html';?>

在footer.html中我有:

<form id="ajax-contact" action="mailer.php" method="post">
          <div id="form-messages"></div>
          <input type="text" name="name" id="name" placeholder="* Nombre y Apellido" class="big-input alt-font">
          <input type="text" name="email" id="email" placeholder="* Email" class="big-input alt-font">
          <textarea name="message" id="message" placeholder=" Mensaje" class="big-input alt-font"></textarea>
          <button type="submit" class="highlight-button-dark btn btn-medium">Enviar</button>
        </form>

然后de AJAX:

(function() {

    var form = $('#ajax-contact');

    var formMessages = $('#form-messages');

    $(form).submit(function(e) {

        e.preventDefault();


        var formData = $(form).serialize();


        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {

            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            $(formMessages).text(response);


            $('#name').val('');
            $('#email').val('');
            $('#message').val('');

        })
        .fail(function(data) {
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');


            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Ocurrio un error! Por favor intenta nuevamente.');
            }
        });

    });

});

和mailer.php

<?php

    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        $name = strip_tags(trim($_POST["name"]));
        $name = str_replace(array("\r","\n"),array(" "," "),$name);


        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $message = trim($_POST["message"]);

        if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Por favor complete todos los campos.";
            exit;
        }


        $recipient = "sebas@gmail.com";

        $subject = "Contacto desde web: $name";

        $email_content = "Nombre y apellido: $name\n";

        $email_content .= "Email: $email\n\n";
        $email_content .= "Mensaje:\n$message\n";

        // Build the email headers.
        $email_headers = "From: $name <$email>";

        // Send the email.
        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.

            echo "Su mensaje se ha envidado exitosamente, nos estaremos comunicando.";
        } else {
            // Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "El mensaje no se ha podido enviar correctamente.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo "There was a problem with your submission, please try again.";
    }

?>

发送邮件时没有显示任何内容 但是没有用......有人帮忙吗? 有一天我开始使用包含...我认为问题是因为de包括

2 个答案:

答案 0 :(得分:1)

我修好了!问题出在AJAX ......无论如何......谢谢。

$("#contactForm").validator().on("submit", function (event) {
    if (event.isDefaultPrevented()) {
        formError();
        submitMSG(false, "Tenes que llenar todo el formulario correctamente!");
    } else {
        event.preventDefault();
        submitForm();
    }
});

function submitForm(){
    var name = $("#name").val();
    var email = $("#email").val();
    var msg_subject = $("#msg_subject").val();
    var message = $("#message").val();

    $.ajax({
        type: "POST",
        url: "form-process.php",
        data: "name=" + name + "&email=" + email + "&msg_subject=" + msg_subject + "&message=" + message,
        success : function(text){
            if (text == "success"){
                formSuccess();
            } else {
                formError();
                submitMSG(false,text);
            }
        }
    });
}

function formSuccess(){
    $("#contactForm")[0].reset();
    submitMSG(true, "Mensaje enviado!")
}

function formError(){
    $("#contactForm").removeClass().addClass('shake animated').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', function(){
        $(this).removeClass();
    });
}

function submitMSG(valid, msg){
    if(valid){
        var msgClasses = "h3 text-center tada animated text-success";
    } else {
        var msgClasses = "h3 text-center text-danger";
    }
    $("#msgSubmit").removeClass().addClass(msgClasses).text(msg);
}

答案 1 :(得分:0)

add()添加ajax代码的结尾

(function() {

    var form = $('#ajax-contact');

    var formMessages = $('#form-messages');

    $(form).submit(function(e) {

        e.preventDefault();


        var formData = $(form).serialize();


        $.ajax({
            type: 'POST',
            url: $(form).attr('action'),
            data: formData
        })
        .done(function(response) {

            $(formMessages).removeClass('error');
            $(formMessages).addClass('success');

            $(formMessages).text(response);


            $('#name').val('');
            $('#email').val('');
            $('#message').val('');

        })
        .fail(function(data) {
            $(formMessages).removeClass('success');
            $(formMessages).addClass('error');


            if (data.responseText !== '') {
                $(formMessages).text(data.responseText);
            } else {
                $(formMessages).text('Ocurrio un error! Por favor intenta nuevamente.');
            }
        });

    });

})();