1

I am trying to create a forget password webpage using PHP and JS. Although when I try add an email address, and click "reset password" nothing happens, and there are no errors in the console. What I want is for the text to appear so the user knows if their password has been reset. But nothing happens and I am unsure what the problem is. If anyone has any ideas can you please let me know. Thanks

<?php
use PHPMailer\PHPMailer\PHPMailer;
require_once "functions.php";

if (isset($_POST['email'])) {
  require_once('config1.php');

    $email = $conn->real_escape_string($_POST['email']);


    $sql = "SELECT user_id FROM zz_login WHERE email='$email'";
    $result = mysqli_query($conn, $sql, MYSQLI_USE_RESULT);
    if (mysqli_num_rows($result) > 0) {
        $token = generateNewString();

        $sql = "UPDATE zz_login SET token='$token',
                            tokenExpire=DATE_ADD(NOW(), INTERVAL 5 MINUTE)
                            WHERE email='$email' ";
        $result = mysqli_query($conn, $sql, MYSQLI_USE_RESULT);

        require_once "PHPMailer/PHPMailer.php";
        require_once "PHPMailer/Exception.php";

        $mail = new PHPMailer();
        $mail->addAddress($email);
        $mail->setFrom("", "");
        $mail->Subject = "Reset Password";
        $mail->isHTML(true);
        $mail->Body = "
            Hi,<br><br>

            In order to reset your password, please click on the link below:<br>
            <a href='
            URL/resetPassword.php?email=$email&token=$token
            '>URL/resetPassword.php?email=$email&token=$token</a><br><br>

            Kind Regards,<br>
            Trip Guider
        ";

        if ($mail->send())
            exit(json_encode(array("status" => 1, "msg" => 'Please Check Your Email Inbox!')));
        else
            exit(json_encode(array("status" => 0, "msg" => 'Something Wrong Just Happened! Please try again!')));
    } else
        exit(json_encode(array("status" => 0, "msg" => 'Please Check Your Inputs!')));
}
?>

Javascript

alert(response);
response= $.parseJSON(response);
if (!response.status)

var email = $("#email");

$(document).ready(function () {
        $('.btn-primary').on('click', function () {
            if (email.val() != "") {
                email.css('border', '1px solid green');

                $.ajax({
                   url: 'forgotPassword.php',
                   method: 'POST',
                   dataType: 'json',
                   data: {
                       email: email.val()
                   }, success: function (response) {
                        if (!response.success)
                            $("#response").html(response.msg).css('color', "red");
                        else
                            $("#response").html(response.msg).css('color', "green");
                    }
                });
            } else
                email.css('border', '1px solid red');
        });
    });
CD6554
  • 21
  • 8
  • Request sent to server ? If yes show the server response. – 4EACH Feb 25 '18 at 11:19
  • @4EACH I am not sure what you mean, could you explain – CD6554 Feb 25 '18 at 11:22
  • What do you get when you run `console.log(email);` or `console.log(email.val());` – The fourth bird Feb 25 '18 at 11:23
  • Use rest client to demonstrate post request and make sure that the server side works as you expect. Next step is to check in browser -> developer tools -> network that you sending the request from client as you expecting. – 4EACH Feb 25 '18 at 11:28
  • @Thefourthbird nothing appears when i add either of them. When I click the button in the network it doesn't show the forgotPassword.php. Is it meant to? – CD6554 Feb 25 '18 at 11:31
  • Are you sure you pass this statement? `if (email.val() != "") {` – The fourth bird Feb 25 '18 at 11:58
  • @Thefourthbird I am getting this error now Warning: mysqli_num_rows(): Function cannot be used with MYSQL_USE_RESULT in URL 13
    e 13 is if (mysqli_num_rows($result) > 0) { –
    – CD6554 Feb 25 '18 at 12:08

2 Answers2

0

You have to parse the json output in jQuery with the following lines:

response= $.parseJSON(response);
  if (!response.status)

Then you can check for the status variable value i.e. whether it is 1 or 0 according to your json_encoded variable in PHP. Also make sure that $mail->send() actualls succeeds in sending the email. Depending on the server (localhost or online) settings, it may not always work.

var email = $("#email");

$(document).ready(function () {
        $('.btn-primary').on('click', function () {
            if (email.val() != "") {
                email.css('border', '1px solid green');

                $.ajax({
                   url: 'forgotPassword.php',
                   method: 'POST',
                   dataType: 'json',
                   data: {
                       email: email.val()
                   }, success: function (response) {
                       response= $.parseJSON(response);
                        if (!response.status)
                          $("#response").html(response.msg).css('color', "red");
                        else
                            $("#response").html(response.msg).css('color', "green");
                    }
                });
            } else
                email.css('border', '1px solid red');
        });
    });

Edit: try sending the email using SMTP. Pasting from here,

$mail = new PHPMailer(); // create a new object
$mail->IsSMTP(); // enable SMTP
$mail->SMTPDebug = 1; // debugging: 1 = errors and messages, 2 = messages only
$mail->SMTPAuth = true; // authentication enabled
$mail->SMTPSecure = 'ssl'; // secure transfer enabled REQUIRED for Gmail
$mail->Host = "smtp.gmail.com";
$mail->Port = 465; // or 587
$mail->IsHTML(true);
$mail->Username = "email@gmail.com";
$mail->Password = "password";
$mail->SetFrom("example@gmail.com");
$mail->Subject = "Test";
$mail->Body = "hello";
$mail->AddAddress("email@gmail.com");

 if(!$mail->Send()) {

  // do your stuff
 } else {
    // do your stuff
 }

The example above uses gmail's smtp. If you use any other mailing service to send the email from, change the values of $mail->Host and $mail->Port accordingly

Istiaque Ahmed
  • 6,072
  • 24
  • 75
  • 141
  • I am getting this error Warning: mysqli_num_rows(): Function cannot be used with MYSQL_USE_RESULT in URL 13
    e 13 is if (mysqli_num_rows($result) > 0) {
    – CD6554 Feb 25 '18 at 12:07
  • @CD6554M use ` $result = mysqli_query($conn, $sql);` instead of ` $result = mysqli_query($conn, $sql, MYSQLI_USE_RESULT);` in PHP code. – Istiaque Ahmed Feb 25 '18 at 12:14
  • It is now coming up with the error Warning: Your version of PHP is affected by a bug that may result in corrupted messages. To fix it, switch to sending using SMTP, disable the mail.add_x_header option in your php.ini, switch to MacOS or Linux, or upgrade your PHP to version 7.0.17+ or 7.1.3+. in URL on line 1364
    I have never seen an error like that before
    – CD6554 Feb 25 '18 at 12:19
  • @CD6554, Edit added – Istiaque Ahmed Feb 25 '18 at 12:28
  • Thanks, although what do I change the username, password and SetFrom to? I want it so that when the user logs in, it knows who they are, rather than hard coding an email address into the php – CD6554 Feb 25 '18 at 12:36
  • You need to change them according to your gmail address if you are using gmail to send the mail – Istiaque Ahmed Feb 25 '18 at 12:37
  • So the username is my email address that I want to send it to, the password is the password for my gmail account, and the SetFrom is my email address again? – CD6554 Feb 25 '18 at 12:40
  • ok so its now saying Uncaught ReferenceError: response is not defined on this line response= $.parseJSON(response); – CD6554 Feb 25 '18 at 12:48
  • before that line just add `alert(response);` and let me know what happens – Istiaque Ahmed Feb 25 '18 at 12:50
  • it didn't do anything, an alert didnt come up – CD6554 Feb 25 '18 at 12:53
  • @CD6554, paste the full `success` callback function here – Istiaque Ahmed Feb 25 '18 at 12:55
  • I don't know what that is.. Do you have discord, just aware that this is a lot of messages under one question – CD6554 Feb 25 '18 at 12:57
  • just thought it would be easier to talk to on that, or skype or something. I updated my question with the js code, although it looks exactly the same as yours – CD6554 Feb 25 '18 at 13:05
  • @CD6554, you are not using my JS code as I see in your question – Istiaque Ahmed Feb 25 '18 at 13:13
  • I am, how is yours differerent? – CD6554 Feb 25 '18 at 13:16
  • You cannot find these 2 lines `response= $.parseJSON(response); if (!response.status)` in your question – Istiaque Ahmed Feb 25 '18 at 13:17
  • they are at the top of the code, where am i supose to put them? – CD6554 Feb 25 '18 at 13:21
  • @CD6554, OMG, just delete everything inside your js file and then paste the code I gave in my answer . I mean the big JS code snippet I gave – Istiaque Ahmed Feb 25 '18 at 13:24
  • so i dont need the response= $.parseJSON(response); if (!response.status) lines? – CD6554 Feb 25 '18 at 13:25
  • You do not need to add it the way you did – Istiaque Ahmed Feb 25 '18 at 13:26
  • that is what i asked previously, where do i put that piece of code? – CD6554 Feb 25 '18 at 13:27
  • Can you please reply to me – CD6554 Feb 25 '18 at 18:09
  • i did do that, but where do i put the response= $.parseJSON(response); if (!response.status)??????? – CD6554 Feb 25 '18 at 22:23
  • no where to put. that is already here `success: function (response) { response= $.parseJSON(response); if (!response.status) $("#response").html(response.msg).css('color', "red"); else $("#response").html(response.msg).css('color', "green"); }`inside the `$.ajax` – Istiaque Ahmed Feb 25 '18 at 22:29
  • I am getting these errors now
    Fatal error: Uncaught Error: Class 'PHPMailer\PHPMailer\SMTP' not found in D:\ URL\PHPMailer.php:1687 Stack trace: #0 D:\URL\PHPMailer.php(1812): PHPMailer\PHPMailer\PHPMailer->getSMTPInstance() #1 D:\URLPHPMailer.php(1725): PHPMailer\PHPMailer\PHPMailer->smtpConnect(Array) #2 DURL\PHPMailer.php(1481): PHPMailer\PHPMailer\PHPMailer->smtpSend('Date: Sun, 25 F...', ' Hi,<br><br>\r\n\t...') #3 D:\URL\PHPMailer.php(1320): PHPMailer\PHPMailer\PHPMailer->po in D:\URL\PHPMailer.php on line 1687
    – CD6554 Feb 25 '18 at 22:44
  • I looked at this but i don't understand any of the answers, they arent the same problem as mine. This is the part of the code that isnt wotking public function getSMTPInstance() { if (!is_object($this->smtp)) { $this->smtp = new SMTP(); } return $this->smtp; } – CD6554 Feb 25 '18 at 23:02
  • https://www.google.com/search?q=Uncaught+Error%3A+Class+%27PHPMailer%5CPHPMailer%5CSMTP%27+not+found+in+PHPMailer.php&ie=utf-8&oe=utf-8&client=firefox-b-ab – Istiaque Ahmed Feb 25 '18 at 23:08
0

It should be very easy to debug what is happening with the following tools:

  • Firefox Debugger Tab in Developer Tools
  • Firefox Network Tab in Developer tools,
  • xdebug for php

With Developer Tools Firefox Network tab, you should be able to look in the sub tab 'xhr' and see all outgoing requests. You can see the outbound data and the response from the server.

With the Debugger, you can step through your JavaScript and check that your logic is good.

With xdebug for php, you can step through your php code when the request hits your server and make sure the logic is good on that end.

Please use your Developer Tools!

Keith Becker
  • 556
  • 1
  • 6
  • 16