如何防止AJAX表单在提交时重定向

时间:2018-01-10 19:15:02

标签: javascript jquery html css ajax

我试图找出如何防止我的表单在提交时重定向。我有它成功发送电子邮件的地方,但它在提交时重定向到/cvg2/contact-submit.php。我不希望它这样做。我希望它将成功/失败消息注入"消息"在表单底部找到的div。

任何帮助?

的index.php

<form id="contact-form" method="post" action="/cvg2/contact-submit.php" role="form">
        <div class="row">
          <div class="col-md-12 col-xs-12 col-sm-12">
            <input name="name" id="name" placeholder="Name" data-validation="alphanumeric" required="required"></input>
          </div>
        </div>
        <div class="row">
          <div class="col-md-12 col-xs-12 col-sm-12">
            <input name="practice" id="practice" placeholder="Practice name"></input>
          </div>
        </div>
        <div class="row">
          <div class="col-md-12 col-xs-12 col-sm-12">
            <input name="city-state" id="city-state" placeholder="City, State" required="required" data-validation="alphanumeric"></input>
          </div>
        </div>
        <div class="row">
          <div class="col-md-12 col-xs-12 col-sm-12">
            <div class="styled-select">
              <select name="position-select">
              <option value="administrative">Administrative</option>
              <option value="physician-shareholder">Physician Shareholder</option>
              <option value="other">Other</option>
            </select>
            </div>
          </div>
        </div>
        <div class="row">
          <div class="col-md-6 col-xs-12 col-sm-12 two-up">
            <input name="phone" id="phone" placeholder="(555)555-5555" required="required" data-validation="custom" data-validation-regexp="^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$" data-validation-error-msg="Invalid Phone Number"></input>
          </div>
          <div class="col-md-6 col-xs-12 col-sm-12 two-up">
            <input name="email" id="email" placeholder="Email" data-validation="email" required="required"></input>
          </div>
        </div>
        <div class="row">
          <div class="col-md-12 col-xs-12 col-sm-12">
            <input type="submit" value="SUBMIT" id="submit">
          </div>
        </div>
        <div class="messages"></div>
      </form>

接触submit.php

<?php

// an email address that will be in the From field of the email.
$from = 'email@domain.com';

// an email address that will receive the email with the output of the form
$sendTo = 'contact@domain.com';

// subject of the email
$subject = 'New Message Received';

// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Name', 'phone' => 'Phone', 'email' => 'Email', 'city-state' => 'Location', 'practice' => 'Practice', 'position-select' => 'Position');


// message that will be displayed when everything is OK :)
$okMessage = 'Contact form successfully submitted!';

// If something goes wrong, we will display this message.
$errorMessage = 'There was an error while submitting the form. Please try again later.';

/*
 *  LET'S DO THE SENDING
 */

// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(0);

try
{

    if(count($_POST) == 0) throw new \Exception('Form is empty');

    $emailText = "You have a new message from your contact form\n=============================\n";


    foreach ($_POST as $key => $value) {
        // If the field exists in the $fields array, include it in the email
        if (isset($fields[$key])) {
            $emailText .= "$fields[$key]: $value\n";
        }
    }

    // All the neccessary headers for the email.
    $headers = array('Content-Type: text/plain; charset="UTF-8";',
        'From: ' . $from,
        'Reply-To: ' . $from,
        'Return-Path: ' . $from,
    );

    // Send email
    mail($sendTo, $subject, $emailText, implode("\n", $headers));

    $responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
    $responseArray = array('type' => 'danger', 'message' => $errorMessage);
}


// if requested by AJAX request return JSON response
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $encoded = json_encode($responseArray);

    header('Content-Type: application/json');

    echo $encoded;
}
// else just display the message
else {
    echo $responseArray['message'];
}

?>

scripts.js

//Form validation
$.validate({
  validateOnBlur : true,
  showHelpOnFocus : false
});

// when the form is submitted
$.on('submit', function (e) {

    // if the validator does not prevent form submit
    if (!e.isDefaultPrevented()) {
        var url = "../cvg2/contact-submit.php";

        // POST values in the background the the script URL
        $.ajax({
            type: "POST",
            url: url,
            // data = JSON object that contact-submit.php returns
            data: $(this).serialize(),
            success: function (data)
            {
                // receive the type of the message: success x danger and apply it
                var messageAlert = 'alert-' + data.type;
                var messageText = data.message;

                // Alert box html
                var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable">' + messageText + '</div>';

                // If have messageAlert and messageText
                if (messageAlert && messageText) {
                    // inject the alert to .messages div in our form
                    $('#contact-form').find('.messages').html(alertBox);
                    // empty the form
                    $('#contact-form')[0].reset();
                }
            }
        });
        return false;
    }
});

3 个答案:

答案 0 :(得分:1)

在学习HTML时,我们学习使用<form>标签 - 作为第一种方式 - 将表单字段保存到数据库。升级网站以使用AJAX时,不需要它们。它们可以被移除。

提交时页面正在卸载,因为<form>代码仍在运行method=POST操作。 <form>代码仍在尝试重定向到此属性中的页面:action="/cvg2/contact-submit.php"

您可以安全地删除这些HTML标记,因为它们仅对表单POST-BACKS有用,这与AJAX调用相反:

<form id="contact-form" method="post" action="/cvg2/contact-submit.php" role="form">
</form>

然后您可以将此标记从<input type="submit" value="SUBMIT" id="submit">更改为<button id="submit">Submit</button>,它仍然会使用jQuery的AJAX调用来发送电子邮件。

使用它:

$("#submit").on('click', function() {...});

如果你真的想使用<form>标签,那么你可以给它一个这样的属性:onSubmit="return false;",它将如下所示:

<form id="contact-form" method="post" action="/cvg2/contact-submit.php" role="form" onSubmit="return false;">
...
</form>

供参考:

答案 1 :(得分:1)

让你的生活轻松我的朋友:

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script src="https://code.jquery.com/jquery-3.2.1.js" integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" crossorigin="anonymous"></script>
    </head>
    <body>
        <form id="contact-form" method="post" role="form">
            <div class="row">
                <div class="col-md-12 col-xs-12 col-sm-12">
                    <input name="name" id="name" placeholder="Name" data-validation="alphanumeric" required="required"></input>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12 col-xs-12 col-sm-12">
                    <input name="practice" id="practice" placeholder="Practice name"></input>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12 col-xs-12 col-sm-12">
                    <input name="city-state" id="city-state" placeholder="City, State" required="required" data-validation="alphanumeric"></input>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12 col-xs-12 col-sm-12">
                    <div class="styled-select">
                        <select name="position-select">
                            <option value="administrative">Administrative</option>
                            <option value="physician-shareholder">Physician Shareholder</option>
                            <option value="other">Other</option>
                        </select>
                    </div>
                </div>
            </div>
            <div class="row">
                <div class="col-md-6 col-xs-12 col-sm-12 two-up">
                    <input name="phone" id="phone" placeholder="(555)555-5555" required="required" data-validation="custom" data-validation-regexp="^(\+\d{1,2}\s)?\(?\d{3}\)?[\s.-]?\d{3}[\s.-]?\d{4}$" data-validation-error-msg="Invalid Phone Number"></input>
                </div>
                <div class="col-md-6 col-xs-12 col-sm-12 two-up">
                    <input name="email" id="email" placeholder="Email" data-validation="email" required="required"></input>
                </div>
            </div>
            <div class="row">
                <div class="col-md-12 col-xs-12 col-sm-12">
                    <input type="submit" value="SUBMIT" id="submit">
                </div>
            </div>
            <div id="error_messages"></div>
        </form>
        <script type="text/javascript">
        $.validate({
          validateOnBlur : true,
          showHelpOnFocus : false
        });
        $("#contact-form").submit(function(e) {
            $.ajax({
                type: "POST",
                url: "../cvg2/contact-submit.php",
                data: $("#contact-form").serialize(),
                success: function (data) {
                    var messageAlert = 'alert-' + data.type;
                    var messageText = data.message;
                    var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable">' + messageText + '</div>';
                    if (messageAlert && messageText) {
                        $('#error_messages').html(alertBox);
                        $('#contact-form')[0].reset();
                    }
                }
            });
            e.preventDefault();
        });
        </script>
    </body>
</html>

接触submit.php:

<?php
    $sendTo = 'contact@domain.com';
    // subject of the email
    $subject = 'New Message Received';
    // form field names and their translations.
    // array variable name => Text to appear in the email
    $fields = array('name' => 'Name', 'phone' => 'Phone', 'email' => 'Email', 'city-state' => 'Location', 'practice' => 'Practice', 'position-select' => 'Position');
    // message that will be displayed when everything is OK :)
    $okMessage = 'Contact form successfully submitted!';
    // If something goes wrong, we will display this message.
    $errorMessage = 'There was an error while submitting the form. Please try again later.';
    /*
     *  LET'S DO THE SENDING
     */
    // if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
    error_reporting(0);
    try {
        if (count($_POST) == 0) throw new \Exception('Form is empty');
        $emailText = "You have a new message from your contact form\n=============================\n";
        foreach ($_POST as $key => $value) {
            // If the field exists in the $fields array, include it in the email
            if (isset($fields[$key])) {
                $emailText .= "$fields[$key]: $value\n";
            }
        }
        // All the neccessary headers for the email.
        $headers = array('Content-Type: text/plain; charset="UTF-8";',
            'From: ' . $from,
            'Reply-To: ' . $from,
            'Return-Path: ' . $from,
        );
        // Send email
        mail($sendTo, $subject, $emailText, implode("\n", $headers));
        $responseArray = array('type' => 'success', 'message' => $okMessage);
    }
    catch (\Exception $e) {
        $responseArray = array('type' => 'danger', 'message' => $errorMessage);
    }
    // if requested by AJAX request return JSON response
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
        $encoded = json_encode($responseArray);
        header('Content-Type: application/json');
        echo $encoded;
    }
    // else just display the message
    else {
        echo $responseArray['message'];
    }
?>

答案 2 :(得分:0)

如果您不进行任何重定向,为什么要为表单设置“操作”标记?

也许你想在点击$('#submit')元素时设置一个AJAX请求来执行?

或者只是将代码放在index.php顶部的“contact-submit.php”中,这样​​它在没有重定向的情况下仍能正常工作?

你的代码只是为你写的内容完美地工作... HTML中的表单元素的“动作标记”用于重定向...所以不要在这里使用它;)