简体   繁体   中英

Jquery and PHP contact form to send email

This page is loaded within another html page when I click ' Contact ' on the horizontal menu.

I had to remove the $(document).ready(function() to get it running at all.

Everything seems to be working except I am not actually receiving the emails. Any ideas?

Thank you!

Here is the contact.html :

<script type="text/javascript">
    $("#submit_btn").click(function() { 
        //collect input field values
        var user_name       = $('input[name=name]').val(); 
        var user_email      = $('input[name=email]').val();
        var user_message    = $('textarea[name=message]').val();

        //simple validation at client's end
        //we simply change border color to red if empty field using .css()
        var proceed = true;
        if(user_name==""){ 
            $('input[name=name]').css('border-color','red'); 
            proceed = false;
        }
        if(user_email==""){ 
            $('input[name=email]').css('border-color','red'); 
            proceed = false;
        }
        if(user_message=="") {  
            $('textarea[name=message]').css('border-color','red'); 
            proceed = false;
        }

        //everything looks good! proceed...
        if(proceed) 
        {
            //data to be sent to server
            post_data = {'userName':user_name, 'userEmail':user_email, 'userMessage':user_message};

            //Ajax post data to server
            $.post('contact_me.php', post_data, function(data){  

                //load success massage in #result div element, with slide effect.       
                $("#result").hide().html('<div class="success">'+data+'</div>').slideDown();

                //reset values in all input fields
                $('#contact_form input').val(''); 
                $('#contact_form textarea').val(''); 

            }).fail(function(err) {  //load any error data
                $("#result").hide().html('<div class="error">'+err.statusText+'</div>').slideDown();
            });
        }

    });

    //reset previously set border colors and hide all message on .keyup()
    $("#contact_form input, #contact_form textarea").keyup(function() { 
        $("#contact_form input, #contact_form textarea").css('border-color',''); 
        $("#result").slideUp();
    });
</script>

<fieldset id="contact_form">
<div id="result"></div>
    <label for="name"><span>Name</span>
    <input type="text" name="name" id="name" placeholder="Enter Your Name" />
    </label>

    <label for="email"><span>Email Address</span>
    <input type="text" name="email" id="email" placeholder="Enter Your Email" />
    </label>

    <label for="message"><span>Message</span>
    <textarea name="message" id="message" placeholder="Enter Your Name"></textarea>
    </label>

    <label><span>&nbsp;</span>
    <button class="submit_btn" id="submit_btn">Submit</button>
    </label>
</fieldset>

And here is the contact_me.php

<?php
if($_POST)
{
    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
        die();
    } 

    $to_Email       = "@gmail.com"; //Replace with recipient email address
    $subject        = 'ContactUS'; //Subject line for emails

    //check $_POST vars are set, exit if any missing
    if(!isset($_POST["userName"]) || !isset($_POST["userEmail"]) || !isset($_POST["userMessage"]))
    {
        die();
    }

    //Sanitize input data using PHP filter_var().
    $user_Name        = filter_var($_POST["userName"], FILTER_SANITIZE_STRING);
    $user_Email       = filter_var($_POST["userEmail"], FILTER_SANITIZE_EMAIL);
    $user_Message     = filter_var($_POST["userMessage"], FILTER_SANITIZE_STRING);

    //additional php validation
    if(strlen($user_Name)<4) // If length is less than 4 it will throw an HTTP error.
    {
        header('HTTP/1.1 500 Name is too short or empty!');
        exit();
    }
    if(!filter_var($user_Email, FILTER_VALIDATE_EMAIL)) //email validation
    {
        header('HTTP/1.1 500 Please enter a valid email!');
        exit();
    }
    if(strlen($user_Message)<5) //check emtpy message
    {
        header('HTTP/1.1 500 Too short message! Please enter something.');
        exit();
    }

    //proceed with PHP email.
    $headers = "From: $user_Email\n" .
    "Reply-To: $user_Email\n" .
    "MIME-Version: 1.0\n" .
    "Content-Type: text/html\n" .
    "X-Mailer: PHP/" . phpversion();

    @$sentMail = mail($to_Email, $subject, $user_Message .'  -'.$user_Name, $headers);

    if(!$sentMail)
    {
        header('HTTP/1.1 500 Couldnot send mail! Sorry..');
        exit();
    }else{
        echo 'Hi '.$user_Name .', Thank you for your email! ';
        echo 'Your email has already arrived in my Inbox, all I need to do is Check it.';
    }
}
?>

Solution: I am using dreamhost and was trying to send mail from a dreamhost server but using a "From: @gmail" account. I had to create a dreamhost @mydomain email and send it from there. I checked the email logs and saw this error: 550 5.7.1 Sender domain not allowed. Can be read about here: http://wiki.dreamhost.com/PHP_mail()

There could be a number of problems here.

Firstly, die() is a poor substitute for proper error handling - at the very least, return a HTTP 500 error like you are doing with some of the other error cases in your code.

Secondly, as RUJordan has stipulated, @ suppresses error messages. You also may not have a mail server; you should (in a development environment only) use the error_reporting(E_ALL) function.

Thirdly, your email headers should be separated by \\r\\n , not \\n as described in the PHP Documentation . Your last header should also have the \\r\\n .

Fourthly, sending email from the user's email address (let's use "abc@example.com") via your server (let's use "yourdomain.com") is a common spam tactic and often results in emails being flagged as spam and/or automatically deleted (Gmail has done this to me). Try sending it from "noreply@yourdomain.com" - your server is now sending email from its own domain, and is hence much more trustworthy. Regardless, you should check your spam folder - but this step lessens the chance of Gmail deleting it before it even reaches your inbox or spam folder.

Finally, mail servers sometimes experience load. Emails may not be delivered immediately; try waiting up to several hours (tumblr once had a delay this long). In addition, if this is a managed hosting platform, check with the host that everything is as it should be.

Not receving email in PHP could be by many reasons. Check if your mail server is working, if your php.ini having correct smtp.host setting. If you use an external email address to receive, (for example google email), your mail server should be able to send message to it. Gmail requires authentication and SMTPS for sending which requires extra setup your mail server. Also, check your spam folder!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM