1
votes

In my quest to validate a form with PHP and $.ajax() and send a mail to my own mail adress having as sender my own gmail adress, as subject the user name and email from the form. Bassically I want the site to notify me that an user left me a message along with his name and adress si I can answer to him. When I try to send I receive an error. I took the script from PHPMailer example but I cannot figure out where the mail body should be. I have the php file:

<?php

error_reporting(E_ALL);
 ini_set('display_errors',true);

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

sleep(1);

 $mail_reg = '/^(?i)(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\  [[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/';

$return = array();
$mesaj = '';


if ($_SERVER['REQUEST_METHOD'] === 'POST') {


    if (empty($_POST['inputName']) || is_numeric($_POST['inputName'])) {

      $mesaj = "Please enter your name!";
     // $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } elseif (empty($_POST['inputEmail']) || !preg_match($mail_reg,   $_POST['inputEmail'])) {

      $mesaj = "Please enter your e-mail!";
    //  $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } elseif (empty($_POST['inputMess'])) {

      $mesaj = "Please tell us something";
     // $return['error'] = true;
      $return['msg'] = 'oops'.$mesaj;
      echo json_encode($return);
      exit();

    } else {

      $mail = new PHPMailer();
      $mail->IsSMTP();          
      $mail->SMTPDebug  = 2;
      $mail->Debugoutput = 'html';
      $mail->Host = "smtp.gmail.com";
      $mail->Port = 587;          
      $mail->SMTPSecure = "tls";
      $mail->SMTPAuth   = true;          
      $mail->Username = "[email protected]";
      $mail->Password = "**********";
      $mail->SetFrom('[email protected]' , 'First Last');         
      $mail->Subject = $_POST['inputName'].'/'.$_POST['inputEmail'].'wrote';
      //$mail->MsgHTML($body);
      $address = '[email protected]';
      $mail->AddAddress($address, "John Doe");
      $mail->Body = $_POST['inputMess'];

      if (!$mail->Send()) {
        $mesaj = 'The message cannot be delivered, please try again later!';
        $return['msg'] = 'The message cannot be delivered, please try again later!';
        echo json_encode($return);
        exit();

      } else {

      $mesaj = 'Thank you for getting in touch. We will contact you!';
     // $return["error"] = false;
      $return["msg"] = 'Thank you for getting in touch. We will contact you! '.$mail-  >ErrorInfo;
      echo json_encode($return);
       exit();
     }
    }
  }


  ?>

   <!DOCTYPE html>

<html lang="en">
 <head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
   <title>NRDC Environmental N.G.O.</title>
  <link href="css/bootstrap.css" rel="stylesheet">

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>

<script src="js/bootstrap.min.js"></script>
    <script src="js/marin.js"></script>
  </head>

<div class="site-wrapper">

  <div class="site-wrapper-inner">

    <div class="cover-container">

      <div class="masthead clearfix">
        <div class="inner">
          <h3 class="masthead-brand">NRDC<br />Save our Planet  O.N.G.</h3>
          <ul class="nav masthead-nav">
            <li><a href="index.html">Home</a></li>
            <li><a href="gallery.html">Gallery</a></li>
            <li class="active"><a href="contact.php">Contact</a></li>
            <li><a href="#">Join Us</a></li>
          </ul>
        </div>
      </div>

      <div class="inner cover">
          <div class="row">
            <div class="col-xs-12" style="text-align:center;font-size:22px;">

             <form method="POST" action="<?php echo $_SERVER['PHP_SELF']; ?>">
                <div class="form-group">
                    <label for="inputName">Your name</label>
                    <input type="text" name="inputName" class="form-control"   id="inputName" placeholder="Name">
                </div>

                <div class="form-group">
                    <label for="inputEmail">Your e-mail</label>
                    <input type="text" name="inputEmail" class="form-control" id="inputEmail" placeholder="E-mail">
                </div>

                <div class="form-group">
                    <label for="inputMess">Your message for us</label>
                    <textarea name="inputMess" class="form-control" id="inputMess">  </textarea>
                </div>

                <button type="submit" name="send" class="btn btn-default">Send</button>
              </form>

              <div id='mess'> </div>

            </div>


          </div>


      </div>

      <div class="mastfoot">
        <div class="inner">
          <p id="footer">©All rights reserved to NRDC, by TaoAppz</p>
        </div>
      </div>

    </div>

  </div>

</div>

JS

$(document).ready(function() {

 var email_reg = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/i;   

$('form').submit(function(event) {

  event.preventDefault();

  if ($('#inputName').val() == '' || $('#inputName').val().length < 2 || !isNaN($('#inputName').val())) {

    alert('Please enter your name');

  } else if (!email_reg.test($('#inputEmail').val())) {

    alert('Please enter a valid e-mail adress');

  } else if ($('#inputMess').val() == '' || !isNaN($('#inputMess').val())) {

    alert('Please tell us something');

  } else {

    var formData = $('form').serialize();
    submitForm(formData);

  }

})


function submitForm(formData) {

    $.ajax({

        type: 'POST',
        url: $('form').action,
        data: formData,
        dataType: 'json',
        cache: false,
        timeout: 7000,
        beforeSend: function() {

      $('#mess').text('Processing...');

    },        
    success: function(data) {


                $('#mess').text(data.msg);              

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {


                $('#mess').text('Error! ' + textStatus + ' ' + errorThrown  + ' ' + 'Please try again later!');

        },
        complete: function(XMLHttpRequest, status) {

            //$('form')[0].reset();


        }

    })
}


  })
1
what error did you get?Praveen Kavuri
I get messaje ' cannot be sent' the first if statement and the json file seems ok. I mention that i work on localhost.tavi_tudor
Did you give proper access from your gmail?Praveen Kavuri
No i didn t know i had to do that. Is it in my gmail account settings.? I will look for it and let you knowtavi_tudor
when you try to send mail from the client keep your mail logged in and it asks you for some access, enable itPraveen Kavuri

1 Answers

1
votes

It was a mistake on my include in php and the '$mail->Debugoutput = 'html' created html output that was pasrsed as JSON.

So I took out the debugg mode from PHPMailer and now I have a nice working contact form using ajax and PHPMailer. Thanks for your help