DevOpsSauce
DevOpsSauce

Reputation: 1387

PHPMailer working from backend, but ajax does not return success message on frontend

I'm sending an email with PHPMailer. It's working just fine. The problem is in the ajax call. If my data returns 'null', the dialog works.

I tried if/else if/else and a switch with the success message set as the default. My console shows no feedback, and no dialog pops up. The only thing that works is the email.

The front end:

<body class="text-center">
<div id="incorrect_email_dialog">
    <h3>Oops! It looks like you entered an incorrect email</h3>
    <h3>Give it another try</h3>
</div>
<div id="correct_email_dialog">
    <h3>Please check the email associated with your account</h3>
    <h3>for instructions to reset your password</h3>
</div>
<div class="container login-container">
    <form id="forgot_pass_form" class="form-signin">
        <img class="login_logo" src="css/images/logos/example_logo72x72.png">
        <h1 class="font-weight-normal">Please enter email</h1>
        <input type="email" id="inputEmail" name="inputEmail" class="form-control" placeholder="Enter email associated with account" required autofocus>
        <button id="login_btn" class="btn btn-lg btn-primary btn-block" type="submit">Submit</button>
        <div class="register-container">
            <p><a class="register-p" href="login.php">Back to Login</a></p>
        </div>
    </form>
</div>
</body>
<script>

    var original_error_dialog = $('#incorrect_email_dialog').html();

        $('#forgot_pass_form').submit(function(e) {
            e.preventDefault();
            console.log(email);
            console.log('Submitted form');
            $.ajax({
                type: 'post',
                url: 'includes/token_send.php',
                dataType: 'json',
                data: $(this).serialize(),
                success: function(data) {
                    console.log(data);
                    switch(data) {
                        case 'Error':
                            console.log('Error');
                            $('#incorrect_email_dialog').html('<h3>Oops. There was a problem</h3>');
                            $('#incorrect_email_dialog').dialog('open');
                            break;
                        case 'null':
                            console.log('Data was null');
                            $('#incorrect_email_dialog').html(original_error_dialog);
                            $('#incorrect_email_dialog').dialog('open');
                            break;
                        default:
                            $('#correct_email_dialog').dialog('open');
                            console.log('All good');
                            break;
                    }
                }
            })
        });

The backend:

<?php

use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\SMTP;
use PHPMailer\PHPMailer\Exception;

require_once '../PHPMailer/src/PHPMailer.php';
require_once '../PHPMailer/src/SMTP.php';
include '../../config/DB.php';

if($_SERVER['REQUEST_METHOD'] === 'POST') {
    $email = $_POST['inputEmail'];

    try { $db = new DB(); } catch (\Exception $e) { $e->getMessage(); }

    $result = $db->getRow('SELECT email FROM users WHERE email=?', [$email]);

    $input_email = $result['email'];

    if($input_email !== null) {
        $to = $input_email;
        $token = bin2hex(random_bytes(8));
        $mail = new PHPMailer();
        $mail->isSMTP();
        $mail->Host = 'localhost';
        $mail->SMTPDebug = 2;
        $mail->setFrom('[email protected]', '');
        $mail->addAddress($to, '');
        $mail->Subject = 'Example Password Reset Request';
        $mail->isHTML(true);
        $mail->Body = '
                <h2 style="padding:10px;background:#ec1414;font-size:16px;color:#fff;">Example Password Reset</h2>
                <br><br>
                <p>Use this link to reset your password</p>
                <br>
                <a style="text-decoration:none!important;" href="http://example.local/reset.php?token='.$token.'&email='.$input_email.'">Click here to reset</a>';
        if(!$mail->send()) {
            echo json_encode('Error');
        } else {
            echo json_encode('Success');
        }
    } else {
        echo json_encode('null');
    }
}

I get the email in my inbox, but nothing after the 'Submitted Form' console.log statement.

I also tried:

case 'Success':
    $('#correct_email_dialog').dialog('open');
    console.log('All good');
    break;

in place of default to no avail.

Upvotes: 0

Views: 204

Answers (1)

DevOpsSauce
DevOpsSauce

Reputation: 1387

Alright, I did some digging and I found my solution as a comment to this question.

I had forgotten that I left

$mail->SMTPDebug = 2;

in the code! All I did was

//$mail->SMTPDebug = 2;

and boom, fixed. Email sends, my jQuery dialog shows up. All is well. :)

I learned something about PHPMailer debug mode and how it interacts with Ajax today. Thanks for pointing me in the right direction, friends.

Here's the console log of the mail dump going away.

enter image description here

And here is the ajax success calling the jQuery Dialog interaction.

enter image description here

Again, thanks for your help.

Upvotes: 1

Related Questions