在实时服务器上,Ajax响应返回整个html而不是echo值,在本地环境中按预期工作

时间:2018-03-15 06:39:05

标签: php jquery ajax

我知道之前已经在这里询问过这类问题,但我尝试过提出的解决方案无济于事。我一直试图弄清楚这几天,但我真的很难过。救命! 我有一个表单正在通过ajax处理php。在php文件中,我回应一个响应,然后应该填充页面上的div。在我的本地环境中,这可以按预期工作。但是,在我的实时服务器上,ajax不是回显字符串,而是返回index.php页面上的整个html。我无法弄清楚为什么会这样。代码:

的index.php:

<!-- index.php -->
<?php include("partials/header.php"); 
    include("functions/register.php"); 
    include("functions/invitefriend.php"); ?>

<!-- ...preceding html.... -->

<!-- Invite a friend form modal -->
        <div class="modal fade" tabindex="-1" role="dialog" id="emailFriend" aria-hidden="true">
          <div class="modal-dialog modal-dialog-centered" role="document">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">Share with a friend or colleague via email: </h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <div class="modal-body">
                <form class="loginForm" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="POST" id="formRefer">
                    <div class="form-group">
                        <label for="fromName">Your full name: </label> <span id="fromNameFeedback"></span>
                        <input class="form-control" type="text" name="fromName" id="fromName" placeholder="Your full name" required autofocus="true">
                    </div>
                    <div class="form-group">
                        <label for="fromEmail">Your email: </label> <span id="fromEmailFeedback"></span>
                        <input class="form-control" type="email" name="fromEmail" id="fromEmail" placeholder="Your email" required>
                    </div>
                    <div class="form-group">
                        <label for="toName">Your friend's name: </label> <span id="toNameFeedback"></span>
                        <input class="form-control" type="text" name="toName" id="toName" placeholder="Your friend's name" required>
                    </div>
                    <div class="form-group">
                        <label for="toEmail">Your friend's email: </label> <span id="toEmailFeedback"></span>
                        <input class="form-control" type="email" name="toEmail" id="toEmail" placeholder="Your friend's email" required>
                    </div>
                    <div class="btn-group" data-toggle="buttons">
                        <p>This person is a: </p>
                      <label class="btn btn-info active">
                        <input type="radio" name="relationship" id="friend" value="friend" autocomplete="off" checked>Friend
                      </label>
                      <label class="btn btn-info">
                        <input type="radio" name="relationship" id="colleague" value="colleague" autocomplete="off">Colleague
                      </label>
                    </div>
                    <div>
                        <div id="message2" class="questions"><?php echo $message2; ?> </div>
                    </div>
                    <div>
                        <div id="message3" class="questions"> </div>
                    </div>
                    <div class="modal-footer">
                        <input class="btn btn-info loginlogin loginBtn" type="submit" name="send" id="referSubmitButton" value="Send" href="javascript:void(0)">
                        <button type="button" class="btn btn-dark" data-dismiss="modal">Cancel</button>
                    </div>
                </form>
              </div>
            </div>
          </div>
      </div>
<?php include("partials/footer.php"); ?>

invitefriend.php:

<?php
//require PHPMailer and autoload
use PHPMailer\PHPMailer\PHPMailer;
require 'vendor/autoload.php';

//Invite a friend via email form handler
$fromName = strip_tags($_POST["fromName"]);
$fromEmail = strip_tags($_POST["fromEmail"]);
$toName = strip_tags($_POST["toName"]);
$toEmail = strip_tags($_POST["toEmail"]);
// $emailMsg = $_POST["emailMsg"];
$relationship = $_POST["relationship"];
$message2 = "";


if ($_SERVER["REQUEST_METHOD"] == "POST"){
    //Validate form
    $err = false;
    //fromEmail cannot be empty or invalid
    if(array_key_exists("fromEmail", $_POST) && PHPMailer::validateAddress($_POST["fromEmail"])){
        $fromEmail = strip_tags($_POST["fromEmail"]);
    } else {
        $err = true;
        echo "<h3>You must provide a valid email address for yourself.</h3>";
    }
    if(array_key_exists("toEmail", $_POST) && PHPMailer::validateAddress($_POST["toEmail"])){
        $toEmail = strip_tags($_POST["toEmail"]);
    } else {
        $err = true;
        echo "<h3>You must provide a valid email address for your friend or colleague.</h3>";
    }
    if(!$err){
        // Insert emails into db (new table for referral addresses)
        $query = "INSERT INTO invitees (`toName`, `toEmail`, `fromName`, `fromEmail`, `date`) VALUES ('".mysqli_real_escape_string($conn, $toName)."', '".mysqli_real_escape_string($conn, $toEmail)."', '".mysqli_real_escape_string($conn, $fromName)."', '".mysqli_real_escape_string($conn, $fromEmail)."', CURDATE())";
        $result = mysqli_query($conn, $query);      
        //and send the email using PHPMailer
        $mail = new PHPMailer();

            //Server settings
            $mail->SMTPDebug = 0;            
            $mail->isSMTP();                                     
            $mail->SMTPAuth = true;   
            $mail->SMTPSecure = 'tls';                
            $mail->Host = 'smtp.stackmail.com';  
            $mail->Username = 'invite@heal-the-nation.com';                
            $mail->Password = 'PMQP1RCngk';                    
            $mail->Port = 587;                                     

            //Recipients
            $mail->setFrom('invite@heal-the-nation.com', 'Heal the Nation');
            $mail->addAddress($toEmail);     // Add a recipient  

            $mail->addReplyTo($fromEmail, $fromName);
            // $mail->addCC('cc@example.com');

            //Add an image in the email body
            $mail->AddEmbeddedImage('./img/HTN_Logo.png', 'HTN_Logo');

            $msg = ''; //Many, many lines of an html email

//Content
            $mail->isHTML(true);                                  
            $mail->Subject = 'An invitation to learn about Heal the Nation: The Healthcare Workers\' Network';
            $mail->Body    = $msg;
            $mail->AltBody = strip_tags($msg);

        if(!$mail->send()) {
            echo "<h3 class='bg-danger text-info'>Unable to send invitation. Please try again.</h3><br>";
            echo "Mailer Error: " . $mail->ErrorInfo;
            //exit();
        } else {
            echo "<h3 class='bg-success text-info'>Invitation sent!</h3>";
            //exit();
        }   
    }
};

?>

invitefriend.js:

$(document).ready(function(){
    var formRefer = $("#formRefer")
    var fromName = $("#fromName").val();
    var fromEmail = $("#fromEmail").val();
    var toName = $("#toName").val();
    var toEmail = $("#toEmail").val();

formRefer.submit(function(event){

        event.preventDefault();

        showSpinner();
        disableButton();

        var fromName = $("#fromName").val();
        var fromEmail = $("#fromEmail").val();
        var toName = $("#toName").val();
        var toEmail = $("#toEmail").val();

        var formData = $(formRefer).serialize();
        var url = $(formRefer).attr('action');

    $.ajax({
            url:url,
            data:formData,
            type:'POST',
            dataType:"text",
        }).done(function(response){
                console.log(response);
                console.log(response.responseText);             

                if($.trim(response) == "<h3 class='bg-danger text-info'>Unable to send invitation. Please try again.</h3><br>"){
                    console.log("The response says unable to send invite....");
                    $("#message3").html(response);
                } else if($.trim(response) == "<h3 class='bg-success text-info'>Invitation sent!</h3>") {
                    console.log("Success!!!");
                    $("#message3").html(response);
                    //Clear the form...

        }).fail(function(data){      
                console.log(data);
                console.log(data.responseText);

                if (data.responseText !== '') {
                    $("#message3").text(data.responseText);
                } else {
                    $("#message3").text('Oops! An error occurred.');
                }
        }); //end ajax request
    }); //end formRefer.submit() function
}); //end document.ready function

所以在我的本地环境中,当我处理这个表单时,我的console.log(响应)给了我表单数据(fromName:John,fromEmail:john@john.com等)和console.log( response.responseText)从php(“<h3 class='bg-danger text-info'>Unable to send invitation. Please try again.</h3>”或“<h3 class='bg-success text-info'>Invitation sent!</h3>”)给出适当的echo值,此responseText填充页面上的div。

但是,当我在我的实时服务器上尝试此操作时,它的行为会有所不同。 console.log(response)返回整个index.php html内容,console.log(response.responseText)返回'undefined',页面上的div保持为空。为什么????我知道表单确实是由php处理的,因为数据被插入数据库并发送电子邮件。所以一定是我的ajax。我在这里和其他地方尝试了许多建议,但没有一个有效。请帮忙!谢谢!!

1 个答案:

答案 0 :(得分:0)

我终于明白了。这确实是我的PHP代码中的一个错误。原来我的文件路径到phpmailer'vendor / autoload'写得不正确(我需要写../vendor/autoload)。那是错误。一旦我修复了文件路径,一切都开始完美了!奇怪的是,错误报告不会简单地告诉我它找不到'vendor / autoload'。