php and email sending ajax

Asked

Viewed 296 times

0

I am trying to send email from my page but it does not return me any message if successful or not, I am using php along with bootstrapvalidation and ajax to forward the information to my php page.

JS

// Contact Form Scripts

$(function() {

$("#contactForm input,#contactForm textarea").jqBootstrapValidation({
preventSubmit: true,
submitError: function($form, event, errors) {
    // additional error messages or events
},
submitSuccess: function($form, event) {
    event.preventDefault(); // prevent default submit behaviour
    // get values from FORM
    var name = $("input#name").val();
    var email = $("input#email").val();
    var assunto = $("input#assunto").val();
    var message = $("textarea#message").val();
    var firstName = name; // For Success/Failure Message
    // Check for white space in name for Success/Fail message
    if (firstName.indexOf(' ') >= 0) {
        firstName = name.split(' ').slice(0, -1).join(' ');
    }
    $.ajax({
        url: "././mail/contact_me.php",
        type: "POST",
        data: {
            name: name,
            assunto:assunto,
            email: email,
            message: message
        },
        cache: false,
        success: function() {
            // Success message
            $('#success').html("<div class='alert alert-success'>");
            $('#success > .alert-success').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
            $('#success > .alert-success')
                .append("<strong>Sua mensagem foi enviada, em breve entraremos em contato.. </strong>");
            $('#success > .alert-success')
                .append('</div>');

            //clear all fields
            $('#contactForm').trigger("reset");
        },
        error: function() {

            // Fail message
            $('#success').html("<div class='alert alert-danger'>");
            $('#success > .alert-danger').html("<button type='button' class='close' data-dismiss='alert' aria-hidden='true'>&times;")
                .append("</button>");
            $('#success > .alert-danger').append("<strong>Sorry " + firstName + ", it seems that my mail server is not responding. Please try again later!");
            $('#success > .alert-danger').append('</div>');
            //clear all fields
            $('#contactForm').trigger("reset");
        },
    });
},
filter: function() {
    return $(this).is(":visible");
},
});

$("a[data-toggle=\"tab\"]").click(function(e) {
e.preventDefault();
$(this).tab("show");
});
});


/*When clicking on Full hide fail/success boxes */
 $('#name').focus(function() {
 $('#success').html('');
 });

HTML

<form action="mail/contact_me.php" method="post"      name="sentMessage"     id="contactForm" novalidate>

                    <div class="row">
                        <div class="form-group col-md-6">
                            <input type="text" class="form-control" placeholder="Nome *" id="name" required data-validation-required-message="Por favor, informe seu nome.">
                            <p class="help-block text-danger"></p>
                        </div>

                        <div class="form-group col-md-6">
                            <input type="email" class="form-control" placeholder="E-mail *" id="email" required data-validation-required-message="Por favor, informe seu e-mail.">
                            <p class="help-block text-danger"></p>
                        </div>

                        <div class="form-group col-md-12">
                            <input type="text" name="assunto" id="assunto" class="form-control" placeholder="ASSUNTO*" required data-validation-required-message="Por favor, informe um assunto.">
                            <p class="help-block text-danger"></p>
                        </div>


                        <div class="col-md-12">
                            <div class="form-group">
                                <textarea class="form-control" rows="5" placeholder="Mensagem *" id="message" required data-validation-required-message="Por favor, insira uma mensagem."></textarea>
                                <p class="help-block text-danger"></p>
                            </div>
                        </div>

                        <div class="clearfix"></div>

                        <div class="form-group">
                            <div id="success">teste</div>
                            <button type="submit" class="btn btn-primary pull-right">ENVIAR MENSAGEM</button>
                        </div>

                    </div>
                </form>

PHP

    <?php

    /*Checa se os campos estao vazios*/
    if (empty($_POST['name']) ||
            empty($_POST['email']) ||
            empty($_POST['assunto']) ||
            empty($_POST['message']) ||
            !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
        echo "No arguments Provided!";
        return false;
    }

    $name = strip_tags(htmlspecialchars($_POST['name']));
    $email_address = strip_tags(htmlspecialchars($_POST['email']));
    $assunto = strip_tags(htmlspecialchars($_POST['assunto']));
    $message = strip_tags(htmlspecialchars($_POST['message']));

    /*Configurações de envio de Email*/

    $to = '[email protected]'; /*Email de Recebimento*/
    $email_subject = "Formulario de Contato"; /*Assunto do Email*/

    $email_body = "Nome: $name\n"
            . "Email: $email_address\n"
            . "Assunto: $assunto\n\n"
            . "Mensagem:\n$message";
    $headers = "From: " . $email_address . "\n"; /*Email de quem enviou*/
    $headers .= "Reply-To: $email_address";
    mail($to, $email_subject, $email_body, $headers);
    return true;
  • Check through an "Alert" or "console.log" if the execution stream is coming to the part where the request is sent. And in the two events of ajax.

  • @mauhumor, checking the console log found this error <br />&#xA;<b>Warning</b>: mail(): Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in <b>C:\xampp\htdocs\farmacia\mail\contact_me.php</b> on line <b>29</b><br />

1 answer

0

See that regardless of the value that mail return, the result is being true, because of return true; at the end of your code. The documentation of mail informs the following:

Returns TRUE if the email has been successfully accepted for delivery, FALSE otherwise. It is important to note that only by the email being accepted for delivery, does not mean that the email will reach the expected destination.

Change the last lines of code to this:

if(@mail($to, $email_subject, $email_body, $headers)) return true; else return false;

Edit: Note: To get the return, put all the code inside a function.

  • In fact the return is wrong both in the question and in your answer, return only works if it is in a function or if it is the return of a include/require. This will not solve the problem of the question return true; else return false; and will not send anything to the response body in Ajax.

  • That’s right William, after completing the answer is that I realized that the code block was not within a function. But I had already done the editing.

  • I have in another project this submission script and it works perfectly. I don’t know why this project isn’t working.

  • @Fabricio this should resolve http://answall.com/q/40858/3635 for its error message <br /> <b>Warning</b>: mail(): Failed to connect to mailserver at &quot;localhost&quot; port 25, verify your &quot;SMTP&quot; and &quot;smtp_port&quot; setting in php.ini or use ini_set() in <b>C:\xampp\htdocs\farmacia\mail\contact_me.php</b> on line <b>29</b><br /> the probable is that you are trying to send directly from your computer and not from a server

  • @Guilhermenascimento, I will make these modifications and post the result, but the strange thing is that I have another project on this same computer that works perfectly with this script.

  • @Open but arrives some email to the recipient? The STMP for sending is configured on your computer?

  • using localhost is not enough, but hosted is. I also tried to host this project and still did not succeed.

Show 2 more comments

Browser other questions tagged

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