0

This is my PHP script:

<?php
    require_once 'PHPMailerAutoload.php';
    $mailApp = new PHPMailer();

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

    $mailApp->From = $email;
    $mailApp->FromName = $name;
    $mailApp->Subject = 'Contacto de http://profile.cv.hsoto.me';
    $mailApp->Body = $message;
    $mailApp->AddAddress('hectorsoto@balamtech.com', 'Hector Soto');
    if($mailApp->Send()){
        echo '<div class="alert alert-success text-center">Su mensaje fue enviado. Gracias por ponerse en contacto conmigo.</div>';
    } else {
        echo '<div class="alert alert-danger text-center">El mensaje no se pudo enviar. Por favor intente de nuevo o mándelo al <a href="mailto:hectorsoto@balamtech.com">hacer click aquí</a>.</div>';
    }

?>

Pretty straightforward, it sends an email.

This is my jquery script:

$('#cmdSendMessage').on('click', function(e){
        e.preventDefault();
        var message, name, email, error = "";
        email = $('#uemail').val();
        message = $('#umessage').val();
        name = $('#uname').val();
        if(email == "" || message == "" || name == ""){
            error = '<div class="alert alert-danger text-center">Uno o más campos están vacíos.</div>';
            $('#error-spot').append(error);
        }else if(!validateEmail(email)){
            error = '<div class="alert alert-danger text-center">El correo no es válido, su formato es incorrecto.</div>';
            $('#error-spot').append(error);
        } else{
            $.post('sendMail.php', 
                   {name : name, message : message, email : email}
                  ).done(
                        function(data){
                        $('#error-spot').append(data); 
                    }).fail(
                        function(data){
                        $('#error-spot').append('<div class="alert alert-danger text-center">Hubo un error y no se pudo mandar el correo. Hacerlo manualmente al <a href="mailto:hectorsoto@balamtech.com">hectorsoto@balamtech.com</a></div>');    
                    })
        }
    });

It processes data and sends the email, however, it thorws an error:

enter image description here

Any ideas why this might be happening?

EDIT:

When looking on the network tab on chrome, they are actually sent:

enter image description here

Which makes this even more weird that they are not being captured on the other side.

CodeTrooper
  • 1,890
  • 6
  • 32
  • 54
  • Check the output of `print_r($_POST);` to determine just what was received by PHP in the post. – Michael Berkowski Sep 01 '14 at 19:19
  • The print_r doesn't print anything, which makes me think nothing is set, however, it is really weird that the mail sends. -__- – CodeTrooper Sep 01 '14 at 19:22
  • May be: http://stackoverflow.com/questions/1282909/php-post-array-empty-upon-form-submission – jonasnas Sep 01 '14 at 19:50
  • - Check your php.ini variables order setting http://php.net/manual/en/ini.core.php#ini.variables-order; - Try `var_dump($_POST)` right at script start to exclude any side effects - Try to post same data into same script using simple HTML form; - Try to use another Windows build, as fresh as possible version, using just `php -S localhost` – Николай Конев Sep 01 '14 at 19:56

3 Answers3

1

Use isset for $_POST or $_GET

Example:

$email = isset($_POST['email']) ? $_POST['email'] : NULL; // warning: Do sanitize

or your script contains too many POST and GET then add following line to top for quick fix -

ini_set('display_errors', 0);

NOTE: if your script contain any other error then it wont display!

HADI
  • 2,829
  • 1
  • 26
  • 26
  • nothing is being sent apparently, since nothing prints when doing print_r on the `$_POST` – CodeTrooper Sep 01 '14 at 19:25
  • So that means nothing is being posted via jQuery. You should fix the JS error. Anyway is there any error showing in console log? – HADI Sep 01 '14 at 19:28
  • no error. take a look at my updated post, they are actually sent since I can see them on the headers in the network tab on chrome dev tools. – CodeTrooper Sep 01 '14 at 19:28
  • before $.post could you please add this line - alert(name+' '+message+' '+email); add let me know if you are getting value or not? – HADI Sep 01 '14 at 19:34
  • Oh i see values are sending, could you please use $.ajax instead of POST like this example http://paste2.org/ztNyVVev – HADI Sep 01 '14 at 19:39
  • There is nothing wrong with $.post - $.ajax is more code and will not change the end result. I believe the problem is that he is using local variable names that are the same as what he is trying to set the post data name as, which I addressed in my answer. – Chad Sep 01 '14 at 19:42
  • I think, there is nothing wrong with the variable name. – HADI Sep 01 '14 at 19:46
  • i found the error. I have to put a semicolon after the fail jqxhr object. That solves it. Who would've thought. – CodeTrooper Sep 01 '14 at 19:48
  • The issue is solved HADI. Thanks for your help. There was a semicolon missing after the `.fail()` callback. – CodeTrooper Sep 01 '14 at 19:51
  • strange! but i guessed there was JS error that why said you to implement ajax instead of post :) anyway good to know that you have solved your problem. – HADI Sep 01 '14 at 19:53
1

The first thing to do is to add ternary operators, or check on the php end that each of the parameters has been sent. (Be sure to sanitize the incoming data, especially when dealing with emails.)

$email = isset($_POST['email']) ? $_POST['email'] : "";
$message = isset($_POST['message']) ? $_POST['message'] : "";
$name = isset($_POST['name']) ? $_POST['name'] : "";

if ($email == "" || $message == "" || $name == "") die(); // something was not sent or direct request was attempted

You may also do this without altering your current code (but please sanitize it):

if (!isset($email) || !isset($message) || !isset($name)) die(); // something was not sent or direct request was attempted

You don't need the error variable if you're just appending - just do the append instead.

It's also a good practice to name the variables something other than what you're sending via the post message. This might be your issue - the post statement might be trying to send the post data under the same name as the value, such as $_POST['test@test.com'] = 'test@test.com' because you're using the same name as the local variable. Change your local variable names (both for good practice and for a potential fix):

$('#cmdSendMessage').on('click', function(e){
    e.preventDefault();
    var uEmail, uMessage, uName, error = "";
    uEmail = $('#uemail').val();
    uMessage = $('#umessage').val();
    uName = $('#uname').val();
    if(uEmail == "" || uMessage == "" || uName == ""){
        $('#error-spot').append('<div class="alert alert-danger text-center">Uno o más campos están vacíos.</div>');

    }else if(!validateEmail(uEmail)){

        $('#error-spot').append('<div class="alert alert-danger text-center">El correo no es válido, su formato es incorrecto.</div>');

    } else{

        $.post('sendMail.php', {email : uEmail, message: uMessage, name: uName}
              ).done(
                    function(data){
                    $('#error-spot').append(data);
                }).fail(
                    function(data){
                    $('#error-spot').append('<div class="alert alert-danger text-center">Hubo un error y no se pudo mandar el correo. Hacerlo manualmente al <a href="mailto:hectorsoto@balamtech.com">hectorsoto@balamtech.com</a></div>');    
                })
    }
});

I'm also not sure why you're appending the data in either case to #error-spot (even if there's no error). You should name your elements more appropriately.

Chad
  • 1,531
  • 3
  • 20
  • 46
  • i found the error. I have to put a semicolon after the fail jqxhr object. That solves it. Who would've thought. Yes I will sanitize it, this is only because I'm testing. I have a validation class ready to do this. Thanks for the advice anyways. – CodeTrooper Sep 01 '14 at 19:47
0

The answer to this question is pretty obvious, yet it happens to most of us at any given point on our programming life.

else{
            $.post('sendMail.php', 
                   {name : name, message : message, email : email}
                  ).done(
                        function(data){
                        $('#error-spot').append(data); 
                    }).fail(
                        function(data){
                        $('#error-spot').append('<div class="alert alert-danger text-center">Hubo un error y no se pudo mandar el correo. Hacerlo manualmente al <a href="mailto:hectorsoto@balamtech.com">hectorsoto@balamtech.com</a></div>');    
                    })
        }

The $.post shorthand method is easily a one line piece of code, the problem is that for readability, programmers tend to put it in many lines as the original post has it.

After chaining the methods, some people often forget to put a semicolon right at the end of the final callback function.

In this case, right at the end of the .fail() callback function.

CodeTrooper
  • 1,890
  • 6
  • 32
  • 54