Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Shreyas Sreenivasa
Shreyas Sreenivasa
7,804 Points

Why doesnt my PHPMailer work?

I tried the exact same thing in another separate file and it works! But when I put it here it doesn't. I guess the code is colliding somewhere. I want it to like display the error message if the credentials are wrong and if they are correct it will send e-mail. If I remove/comment the php mailer code it works. So if I add the php-mailer code it doesn't work.

Here's my activate.php:

<!DOCTYPE html>
<html>
  <head>
    <title>NHG</title>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <link type="text/css" rel="stylesheet" href="css/normalize.css"/>
    <link type="text/css" rel="stylesheet" href="css/style.css"/>
    <link type="text/css" rel="stylesheet" href="css/resposive.css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script src="JS/script.js"></script>
    <script src="JS/activate.js"></script>
  </head>
  <body>
    <div id="abhimanyu">
      <p>"Life will test you but remember this, when you walk up a mountain your legs get stronger"</p>
    </div>
    <div id="arjun">
      <p>"There is no such thing as a failed experiment, only experiments with unexpected outcomes"</p>
    </div>
    <br>
    <div id="bheem">
      <p>"Do not look where you fell, but where you slipped."</p>
    </div>
    <div id="eklavya">
      <p>"Sometimes life touches one person with a bouquet and another with a thorn bush, but the first may find a wasp in the flowers, and the second may discover roses among the thorns."</p>
    </div>
    <header>
            <div id="main-head">    
              <a href="#" id="main-heading"><h2><span>sKool</span><span>Talk</span></h2></a>
            </div>
    </header>
    <section>
      <div id="container">
        <div id="wrapper">
          <img src="https://i.imgsafe.org/a40bbe047e.png" alt="avatar" id="schoolAvatar" align="middle">
          <div id="activateAccountDiv">
            <form id="activateAccount" data-param-uri="activate">
                <input type="hidden" name="action" value="Activated"/>
              <input type="text" name="activateAdmissionNumber" id="activateAdmissionNumber" placeholder="Enter your asmission number..."/>
              <br>
              <input type="password" name="activatePassword" id="activatePassword" placeholder="Enter your generated Password...">
              <br>
              <button type="submit" id="activateSubmitButton">
                <p>Next</p>
              </button> 
              <br>
              <p id="activateErrorMessage"></p>
            </form>
            <br>
          </div>
        </div>
      </div>
    </section>
    <br>
    <footer>
      <div class="footerHR">
      </div>
    </footer>
  </body>
</html>

Heres my JS/activate.js:

    var _Form, _Site = {_Resp: 'default_global'};

    $(document).ready(function() {

      $("#activateAdmissionNumber").on('blur',function(e){
          $(document).find("#activateErrorMessage").html("");
      });
      $("#activatePassword").on('blur',function(e){
          $(document).find("#activateErrorMessage").html("");
      });

      $("#activateAccount").on('submit',function(e){
        e.preventDefault();
        $data = $(this).serialize();
        $URL = 'php/'+$(this).attr('data-param-uri')+'.php';
        _Form.__Link($URL, $data,function (return_data){
          if(typeof (return_data.url) !== 'undefined' && return_data.success === true ){
            $(document).find("#activateErrorMessage").html("");
            window.location.href = return_data.url;
          }else{
            $(document).find("#activateErrorMessage").html(return_data.msg);
            }
          });
      });  
       _Form = {
          __Link: function ($url, $data, callback){
            $.ajax({
              url: $url,
              data: $data,
              type: 'POST',
              dataType: 'json',
              processData: false,
              contentType: 'application/x-www-form-urlencoded',
              cache:false,
              success: function (data) {
                        callback(data);
                       }
              });
          }
        }
    });

Heres my PHP/activate.php:

    <?php
      require_once('connect.php');
      if(isset($_POST)) {  
          if($_POST['action'] === "Activated"){
              unset($_POST['action']);
            echo activateUser($_POST);exit;
          }      
          // you can use this if  statement as your method filter logic
      }

      function activateUser($FORMDATA){
          global $conn; // define you db coonection use every time if you use further my code style

          if(empty($FORMDATA)){ $RESP['success'] = false;$RESP['msg'] = "NullData";return json_encode($RESP);} //  cross check data is empty or not

          $sql = "SELECT * FROM Users WHERE AdmissionNumber='".$FORMDATA['activateAdmissionNumber']."' AND Password='".$FORMDATA['activatePassword']."';";
          $result = $conn->query($sql);
          $row = $result->fetch_assoc();

          //if only one user is there than is valid
          if(($result->num_rows) == 1){
              $sql =  "UPDATE `NewHorizonGurukul`.`Users` SET `Activate`='1' WHERE `ID`='".$row['ID']."';";

              require_once '../phpmailer/PHPMailerAutoload.php';

              $mail = new PHPMailer;

              //$mail->SMTPDebug = 3;                               // Enable verbose debug output

              $mail->isSMTP();                                      // Set mailer to use SMTP
              $mail->Host = 'smtp.gmail.com';  // Specify main and backup SMTP servers
              $mail->SMTPAuth = true;                               // Enable SMTP authentication
              $mail->Username = 'shreyas.sreenivasa@gmail.com';                 // SMTP username
              $mail->Password = 'jaihind123';                           // SMTP password
              $mail->SMTPSecure = 'tls';                            // Enable TLS encryption, `ssl` also accepted
              $mail->Port = 587;                                    // TCP port to connect to

              $mail->setFrom('from@example.com', 'Mailer');
              $mail->addAddress('shreyas.sreenivasa@gmial.com', 'Joe User');     // Add a recipient
              $mail->addAddress('ellen@example.com');               // Name is optional
              $mail->addReplyTo('info@example.com', 'Information');
              $mail->addCC('cc@example.com');
              $mail->addBCC('bcc@example.com');

              $mail->addAttachment('/var/tmp/file.tar.gz');         // Add attachments
              $mail->addAttachment('/tmp/image.jpg', 'new.jpg');    // Optional name
              $mail->isHTML(true);                                  // Set email format to HTML

              $mail->Subject = 'Here is the subject';
              $mail->Body    = 'This is the HTML message body <b>in bold!</b>';
              $mail->AltBody = 'This is the body in plain text for non-HTML mail clients';

              if(!$mail->send()) {
                echo 'Message could not be sent.';
                echo 'Mailer Error: ' . $mail->ErrorInfo;
              } else {
                echo 'Message has been sent';
              }

              $RESP['success'] = true;
              $RESP['msg'] = "Your acount has been activated!";
              $RESP['url'] = 'NHGLogin.php';
          }else{
              $RESP['success'] = false;
              $RESP['msg'] = "Please enter a valid Username or Password!";
          }
          return json_encode($RESP);// Js Accept Json Responses
      }
    ?>

Thank you in advance!