php表单操作到不同的页面然后返回ajax调用不起作用

时间:2017-04-14 09:31:24

标签: php ajax

场景是这样的: 在第一个php页面上,我有一个简单的表单,其中包含一个处理表单验证的php类的动作,然后在电子邮件中发送表单值。根据发送电子邮件或表单验证的成功或失败,我有自定义消息,我在初始表单页面上显示。

我正在使用ajax调用表单;我遇到的问题是,当我第一次登陆表单页面并单击提交按钮时,页面刷新就像不是异步调用,但第二次正常工作;意思是没有页面刷新。

在ajax调用代码下面;我使用的是PHP 7和最新的Jquery(3.2.1)

/*----------------------------------------------------*/
/*  contact form
 ------------------------------------------------------*/

$('form[name=contactForm]').submit(function (e) {
    e.preventDefault();

    var hidden = $('#baseurl');
    var baseUrl = hidden.val();       

    // AJAX request
    $.ajax({
        url: this.action,
        type: this.method,
        data: $(this).serialize(),                          
        beforeSend: function ()
        {
            $('.image-loader').show();
        },
        success: function (data)
        {
            var Result = $.trim(data).toLowerCase();
            $('#message-warning').hide();

            $('.image-loader').hide(); // hide the loading message              
            if (Result === "ok")
            {
                $('#message-success').show();
                $('#message-success').stop().fadeOut(6000, "linear");

            } else
            {
                $('#message-success').hide();
                $('#message-warning').css({'display': 'block'});

                if (Result !== "")
                {
                    $('#message-warning').html(Result);
                } else
                {
                    $('#message-warning').html("<p>Your email has not being sent.</p><p>If this problem occurs again please do send us an email at massimo@mywaydigitalhealth.co.uk.</p>");
                }
                $('#message-warning').show();
                //$('#message-warning').stop().fadeOut(10000, "linear");
            }


            window.location = baseUrl; 
            return false;

        },
        error: function ()
        {
            //TODO log errorThrown.responseText which contains error message and stack trace

            $('.image-loader').hide(); // hide the loading message
            $('#message-success').hide();
            $('#message-warning').css({'display': 'block'});
           // $('#message-warning').html(errorThrown.responseText);
            $('#message-warning').html('<p>An error occurred while attempting to send your message.</p> <p>We apologise for the inconvenience.</p>\n\<p>If this problem occurs again please do send us an email at massimo@mywaydigitalhealth.co.uk.</p>');                            
            $('#message-warning').show();
            //$('#message-warning').stop().fadeOut(10000, "linear");

            window.location = baseUrl;   
            return false;

        },          
    });
});

================================= HTML

<form name="contactForm" id="contactForm" method="post" action="inc/sendEmail.php">
        <fieldset>
            <div class="row">
                <div class="six columns mob-whole">
                    <label for="contactFname">First Name <span class="required">*</span></label>
                    <input name="contactFname" type="text" id="contactFname" placeholder="First Name"   />
                </div>

                <div class="six columns mob-whole">
                    <label for="contactLname">Last Name <span class="required">*</span></label>
                    <input name="contactLname" type="text" id="contactLname" placeholder="Last Name"  />
                </div>
            </div>

            <div class="row">
                <div class="six columns mob-whole">
                    <label for="contactEmail">Email <span class="required">*</span></label>
                    <input name="contactEmail" type="text" id="contactEmail" placeholder="Email" />
                </div>

                <div class="six columns mob-whole">
                    <label for="contactSubject">Subject</label>
                    <input name="contactSubject" type="text" id="contactSubject" placeholder="Subject"  />
                </div>
            </div>

            <div class="row">  <div class="twelve columns">
                    <label for="contactMessage">Message <span class="required">*</span></label>
                    <textarea name="contactMessage" id="contactMessage" placeholder="Your Message" rows="10" cols="50" ></textarea>
                </div>
            </div>

            <div>
                <input type="submit" value="Send Message" class="submit full-width" />
            </div>
        </fieldset> 
    </form> <!-- /contactForm -->

========================= PHP class

    <?php

include_once('../config.php');
include_once ('../lib/SwiftMailer/swift_required.php');

if ($_POST)
{
$referer = $_SERVER['HTTP_REFERER'];
$referer .= "#contact";


$FormValidated;
$SwiftMsg;
$IsLocal;
$response = "";
$transport;
$mailer;
$SendFormTo = "xxxxxxxxxxxxxxxxxxxxx";
$SendFormToName = "xxxxxxxxxxx";

$fname;
$lname;
$email;
$subject;
$messageText;
$BodyEMail;

$fname = trim(stripslashes($_POST['contactFname']));
$lname = trim(stripslashes($_POST['contactLname']));
$email = trim(stripslashes($_POST['contactEmail']));
$subject = trim(stripslashes($_POST['contactSubject']));
$messageText = trim(stripslashes($_POST['contactMessage']));

$validator = new FormValidators();

//required
$validator->addValidation("contactFname", "req", "Please fill in your name");
$validator->addValidation("contactLname", "req", "Please fill in your surname");
$validator->addValidation("contactEmail", "req", "Please fill in your Email");
$validator->addValidation("contactSubject", "req", "Please fill in the subject");
$validator->addValidation("contactMessage", "req", "Please fill in your email");

//only alphabet, numbers and spaces allowed
$validator->addValidation("contactFname", "alnum_s", "Please enter only alphanumeric characters fill in your name");
$validator->addValidation("contactLname", "alnum_s", "Please enter only alphanumeric characters in your surname");
$validator->addValidation("contactSubject", "alnum_s", "Please enter only alphanumeric characters in the subject");

//len
$validator->addValidation("contactFname", "minlen=2", "Please enter a name longer than 2 characters");
$validator->addValidation("contactLname", "minlen=2", "Please enter a surname longer than 2 characters");
$validator->addValidation("contactSubject", "minlen=2", "Please enter a subject longer than 2 characters");
$validator->addValidation("contactMessage", "minlen=15", "Please enter a message longer than 15 characters");

//format
$validator->addValidation("contactEmail", "email", "Please enter a valid email address");

$FormValidated = $validator->ValidateForm();

if ($FormValidated)
{
// Set Name
$name = $fname . " " . $lname;

//concatenate the email body message
$BodyEMail = "<h1>MyWay Digital health enquiry form</h1>";
$BodyEMail .= "<p>Enquiry sent from: <strong>" . $name . "</strong></p>";
$BodyEMail .= "<p>Subject: <strong>" . $subject . "</strong></p>";
$BodyEMail .= "<h2>Message</h2>";
$BodyEMail .= "<p>" . $messageText . "</p>";

// Create the Transport
$transport = Swift_SmtpTransport::newInstance('xxxxxx', 465, 'ssl')
->setUsername('xxxxxxxxxxxxxx')
->setPassword('xxxxxxxxxx');

// Create the Mailer using your created Transport
$mailer = Swift_Mailer::newInstance($transport);

// Create a message
$SwiftMsg = Swift_Message::newInstance();

$IsLocal = is_localhost();
if ($IsLocal)
{
$SwiftMsg->setFrom(array('xxxxxxxxxx' => 'MyWay Digital Health'));
}
else
{
$SwiftMsg->setFrom(array('xxxxxxxxxx' => 'MyWay Digital Health'));
}

$SwiftMsg->setSubject($subject);
$SwiftMsg->setFrom(array('xxxxxxxxxxxx' => 'MyWay Digital Health'));
$SwiftMsg->setTo(array($SendFormTo => $SendFormToName));
$SwiftMsg->setBody($BodyEMail, 'text/html');

// Send the message
$response = $mailer->send($SwiftMsg);

if ($response == 1)
{
$response = 'OK';
}
} # end if - no validation error
else
{

$error_hash = $validator->GetErrors();

foreach ($error_hash as $inpname => $inp_err)
{
$response .= "<p>$inp_err</p>";
}
} # end if - there was a validation error  

echo $response;
}
?>

0 个答案:

没有答案