感谢您在表单提交后进行页面重定向

时间:2018-03-12 12:12:43

标签: php ajax forms url-redirection

我需要在用户提交表单后重定向到感谢页面。我搜索并尝试了很多东西,结果总是一样,邮件服务器收到邮件,但浏览器没有转到另一页,也没有清理表单。

所以index.html有这样的形式:

<form action="process.php" id="contact-form" method="post">
<div class="row">
    <div class="col-xs-12 col-sm-6">
        <div class="form-group">
            <label for="form-name" class="sr-only">Nombre</label>
            <input type="text" class="form-control" id="form-name" name="form-name" placeholder="Nombre" required>
        </div>
        <div class="space-10"></div>
    </div>
    <div class="col-xs-12 col-sm-6">
        <div class="form-group">
            <label for="form-email" class="sr-only">Email</label>
            <input type="email" class="form-control" id="form-email" name="form-email" placeholder="Email" required>
        </div>
        <div class="space-10"></div>
    </div>
    <div class="col-xs-12">
        <div class="form-group">
            <label for="form-subject" class="sr-only">Asunto</label>
            <input type="text" class="form-control" id="form-subject" name="form-subject" placeholder="Asunto" required>
        </div>
        <div class="space-10"></div>
    </div>
    <div class="col-xs-12">
        <div class="form-group">
            <label for="form-message" class="sr-only">comment</label>
            <textarea class="form-control" rows="6" id="form-message" name="form-message" placeholder="Mensaje" required></textarea>
        </div>
        <div class="space-10"></div>
        <button class="btn btn-link no-round text-uppercase" type="submit">Enviar</button>
    </div>
</div>

process.php有这个:

<?php
// Configure your Subject Prefix and Recipient here
$subjectPrefix = 'Consulta EMPRENDE';
$emailTo       = 'emprende@eibanezyasociados.com';
$errors = array(); // array to hold validation errors
$data   = array(); // array to pass back data
if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name    = stripslashes(trim($_POST['name']));
    $email   = stripslashes(trim($_POST['email']));
    $subject = stripslashes(trim($_POST['subject']));
    $message = stripslashes(trim($_POST['message']));
if (empty($name)) {
    $errors['name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Email is invalid.';
}
if (empty($subject)) {
    $errors['subject'] = 'Subject is required.';
}
if (empty($message)) {
    $errors['message'] = 'Message is required.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
    $data['success'] = false;
    $data['errors']  = $errors;
} else {
    $subject = "$subjectPrefix $subject";
    $body    = '
    <strong>Nombre: </strong>'.$name.'<br />
    <strong>Email: </strong>'.$email.'<br />
    <strong>Mensaje: </strong>'.nl2br($message).'<br />
    ';
    $headers  = "MIME-Version: 1.1" . PHP_EOL;
    $headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
    $headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
    $headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
    $headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
    $headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . "<$email>" . PHP_EOL;
    $headers .= "Return-Path: $emailTo" . PHP_EOL;
    $headers .= "Reply-To: $email" . PHP_EOL;
    $headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
    $headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
    mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
    $data['success'] = true;
    $data['message'] = 'Muchas Gracias. Su mensaje se envió con éxito. Estudiaremos su propuesta a la mayor brevedad posible y contactaremos con usted con la solución que más se ajuste a sus necesidades.';
}
// return all our data to an AJAX call
echo json_encode($data);

}

所以我尝试评论最后一行并写下来:

// return all our data to an AJAX call
/*echo json_encode($data);*/

//redirection
header("Location:http://www.emprende.eibanezyasociados.com/gracias.html");

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

看了一下您的实际网站后,您似乎正在使用$.ajax帖子请求,下次请将其添加到您的问题中。

当您使用jQuery发布表单时,无法使用PHP重定向页面,您必须从PHP文件json_encode($data)

返回JSON数据,即process.php

使用JSON.Parse(data)传递JSON响应,检查data['success']是否为真,如果是,则使用javascript window.location = "http://www.emprende.eibanezyasociados.com/gracias.html";重定向页面

因此,您用于发布表单contact-form.js的Javascript文件应如下所示:

(function ($, window, document, undefined) {
    'use strict';

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

    $form.submit(function (e) {
        // remove the error class
        $('.form-group').removeClass('has-error');
        $('.help-block').remove();

        // get the form data
        var formData = {
            'name' : $('input[name="form-name"]').val(),
            'email' : $('input[name="form-email"]').val(),
            'subject' : $('input[name="form-subject"]').val(),
            'message' : $('textarea[name="form-message"]').val()
        };

        // process the form
        $.ajax({
            type : 'POST',
            url  : 'process.php',
            data : formData,
            dataType : 'json',
            encode : true
        }).done(function (data) {
            // handle errors
            if (!data.success) {
                if (data.errors.name) {
                    $('#name-field').addClass('has-error');
                    $('#name-field').find('.col-lg-10').append('<span class="help-block">' + data.errors.name + '</span>');
                }

                if (data.errors.email) {
                    $('#email-field').addClass('has-error');
                    $('#email-field').find('.col-lg-10').append('<span class="help-block">' + data.errors.email + '</span>');
                }

                if (data.errors.subject) {
                    $('#subject-field').addClass('has-error');
                    $('#subject-field').find('.col-lg-10').append('<span class="help-block">' + data.errors.subject + '</span>');
                }

                if (data.errors.message) {
                    $('#message-field').addClass('has-error');
                    $('#message-field').find('.col-lg-10').append('<span class="help-block">' + data.errors.message + '</span>');
                }
            } else {
                // display success message
                $form.html('<div class="alert alert-success">' + data.message + '</div>');
                window.location = "http://www.emprende.eibanezyasociados.com/gracias.html";
            }
        }).fail(function (data) {
            // for debug
            console.log(data)
        });

        e.preventDefault();
    });
}(jQuery, window, document));

您的PHP文件process.php应如下所示:

<?php
// Configure your Subject Prefix and Recipient here
$subjectPrefix = 'Consulta EMPRENDE';
$emailTo       = 'emprende@eibanezyasociados.com';
$errors = array(); // array to hold validation errors
$data   = array(); // array to pass back data
if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $name    = stripslashes(trim($_POST['name']));
    $email   = stripslashes(trim($_POST['email']));
    $subject = stripslashes(trim($_POST['subject']));
    $message = stripslashes(trim($_POST['message']));
if (empty($name)) {
    $errors['name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    $errors['email'] = 'Email is invalid.';
}
if (empty($subject)) {
    $errors['subject'] = 'Subject is required.';
}
if (empty($message)) {
    $errors['message'] = 'Message is required.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
    $data['success'] = false;
    $data['errors']  = $errors;
} else {
    $subject = "$subjectPrefix $subject";
    $body    = '
    <strong>Nombre: </strong>'.$name.'<br />
    <strong>Email: </strong>'.$email.'<br />
    <strong>Mensaje: </strong>'.nl2br($message).'<br />
    ';
    $headers  = "MIME-Version: 1.1" . PHP_EOL;
    $headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
    $headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
    $headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
    $headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '@' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
    $headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . "<$email>" . PHP_EOL;
    $headers .= "Return-Path: $emailTo" . PHP_EOL;
    $headers .= "Reply-To: $email" . PHP_EOL;
    $headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
    $headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
    mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
    $data['success'] = true;
    $data['message'] = 'Muchas Gracias. Su mensaje se envió con éxito. Estudiaremos su propuesta a la mayor brevedad posible y contactaremos con usted con la solución que más se ajuste a sus necesidades.';
}
// return all our data to an AJAX call
echo json_encode($data);