Phpmailer contact form does not work

Asked

Viewed 206 times

2

I’m using the Phpmailer class to send emails, only every time I click the send button it keeps the message forever in "Sending your message...". I don’t know if the problem is in AJAX or mine mail.php.

In the console of the following error:

SyntaxError: Unexpected token < in JSON at position 0
    at JSON.parse (<anonymous>)
    at m.parseJSON (jquery-1.11.1.min.js:4)
    at Pc (jquery-1.11.1.min.js:4)
    at x (jquery-1.11.1.min.js:4)
    at XMLHttpRequest.b (jquery-1.11.1.min.js:4)

Follow my code below:

<form role="form" class="Main__Form--contact" method="post" action="mail.php">
                <div class="Input__groups">
                    <input type="text" name="name" id="name" placeholder="Insira seu nome" required>
                </div>
                <div class="Input__groups">
                    <input type="email" name="email" id="email" placeholder="Insira seu e-mail" required>
                </div>
                <div class="Input__groups">
                    <input type="text" name="subject" id="subject" placeholder="Insira o assunto" required>
                </div>
                <div class="Input__groups">
                    <textarea name="message" id="message" rows="5" placeholder="Escreva sua mensagem" required></textarea>
                </div>
                <button type="submit" class="Button--blue Button_submit">Enviar</button>
            </form>

AJAX I am using:

var form = $('.Main__Form--contact');
     form.submit(function(event){
     event.preventDefault();
     var form_status = $('<div class="Main__Form--status"></div>');

     var data = {
        name: $('#name').val(),
        email: $('#email').val(),
        subject: $('#subject').val(),
         message: $('#message').val()
    };

    $.ajax({
        url: $(this).attr('action'),
        type: "POST",
        dataType: "json",
        data: {'data': data},
        beforeSend: function(){
            form.prepend( form_status.html('<p class="text---white Column---left"><i class="fa fa-spinner fa-spin"></i> Enviando sua mensagem...</p>').fadeIn() );
        },
        success: function (d) {
        d = JSON.parse(d);
        if(d == 1){
                form_status.html('<p class="Column---left" style="color: #00ff00">Mensagem enviada com sucesso!</p>').delay(3000).fadeOut();
                $('#name').val("");
                $('#email').val("");
                $('#subject').val("");
                $('#message').val("");
            } else{
                form_status.html('<p class="Column---left" style="color: #ff0000">Ocorreu um erro ao tentar enviar a mensagem, tente novamente!</p>').delay(3000).fadeOut();
            }
        },
        error: function (xhr, status, error) {
            console.log(error); 
        }
    });
});

My PHP mail.php file:

<?php
   include_once "../PHPMailer/class.phpmailer.php";
   include_once "../PHPMailer/class.smtp.php";

   $data       = $_POST['data'];
   $name       = $data['name'];
   $subject    = $data['subject'];
   $message    = $data['message'];
   $email      = $data['email'];

   $mail = new PHPMailer(); 

   $mail->isSMTP();
   $mail->isHTML(true);
   $mail->Mailer = 'smtp';
   //$mail->SMTPDebug = 2;
   $mail->SMTPAuth = true;
   $mail->CharSet = 'UTF-8';
   $mail->SingleTo = true;

   //configuração do email
   $mail->Port = '587'; 
   $mail->Host = 'xxxxx';
   $mail->Username = '[email protected]'; 
   $mail->Password = 'xxxxxx';
   $mail->From     = '[email protected]';
   $mail->FromName = 'Atendimento';

   $destinatario = '[email protected]';
   $mail->addAddress($destinatario);
   $mail->addReplyTo($email);

   $mail->Subject = $subject;

   $remetente = '-=-=-=- Formulário de Contato -=-=-=-';
   $remetente = $remetente . '<br> Enviado por: '. $name;
   $remetente = $remetente . '<br> E-mail: '. $email;

   $documento = $message. ' <br><br><br><br>' . $remetente;
   $mail->Body = $documento;

   if (!$mail->send()) {
       //echo 'Erro:' . $mail->ErrorInfo;
       echo json_encode(0);
       exit;
   }
   else {
    echo json_encode(1);
    exit;
   }

2 answers

1

You are returning from PHP two possible values:

echo json_encode(0); and echo json_encode(1);

Which is weird because it’s not JSON.

You want to simply see if the variable returned in d is 0 or 1, does not need or specify the dataType in Ajax and PHP change the echo for echo 1; and echo 0; and excludes the line d = JSON.parse(d);.

Edit

Exchange the:

var data = {
    name: $('#name').val(),
    email: $('#email').val(),
    subject: $('#subject').val(),
     message: $('#message').val()
};

For:

var data = form.serialize();

Which will send all form fields. And in data: change:

data: {'data': data},

For:

data: data,
  • Didn’t solve buddy

  • @darknone after changes, which returns in Ajax?

  • The following error: VM94:1 Uncaught Syntaxerror: Unexpected token < in JSON at position 0 at JSON.parse (<Anonymous>) at Object.Success ((index):522) at j (jquery-1.11.1.min. js:2) at Object.fireWith [as resolveWith] (jquery-1.11.1.min. js:2) at x (jquery-1.11.1.min. js:4) at Xmlhttprequest. b (jquery-1.11.1.min. js:4) Index line 522: d = JSON.parse(d);

  • @darknone Delete the line d = JSON.parse(d);

  • Now it shows "An error occurred while trying to send the message!" and no error on the console apparently

  • @darknone So the code is correct, it’s returning 0. You have to check in PHP what you are doing to fall in 0.

  • @darknone I think the problem may be in data

  • @darknone This date is weird. I’ll try to reproduce here...

  • The error seems to be in the Phpmailer class, it returns the error in Network saying it was not found in the specified directory or is invalid.

  • As for this error I was able to solve, now what is giving is: Warning: stream_socket_enable_crypto(): SSL Operation failed with code 1. Openssl Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:Certificate Verify failed in C:wamp64 www class phpmailer class.smtp.php on line <i>344</i>

  • Each time I fix an error, another appears. Now ta giving 500 (Internal Server Error)

  • @darknone See the Edit I put in the question. This makes it easy to submit the form. If there is still an error coming from PHP, the problem is in PHP.

  • It returns this error on the localhost, but when I test on the domain it simply from the Internal server error in the console and returns no error in PHP on network.

Show 8 more comments

0

From a search on how to find the "error_log" of your PHP server, so you can get more details of the error that is happening.

  • Hello, thank you for the reply friend. .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.