Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

PHP

Need help with AJAX contact form

I'm creating a personal portfolio website, complete with contact form. It's a one page website so I'm striving for a nifty AJAX contact form. I've written up the HTML, PHP and even JS but they don't seem to want to work together.

Here's the HTML for the form:

<!-- Email -->
         <article id="email" class="panel">

            <header>
              <h2>Email Me</h2>
            </header>
            <form action="send.php" method="post">
              <div id="contactForm">
                <div class="row half">
                  <div class="6u">
                    <input type="text" class="text" name="name" placeholder="Name" />
                    <!--Error message-->
                    <span class="error" id="err-name">please enter  your name</span>
                    <!--End error message-->
                  </div>
                  <div class="6u">
                    <input type="text" class="text" name="email" placeholder="Email" />
                    <!--Error message-->
                    <span class="error" id="err-email">please enter your e-mail</span>
                    <span class="error" id="err-emailvld">e-mail is not a valid format</span>
                    <!--End error message-->
                  </div>
                </div>
                <div class="row half">
                  <div class="12u">
                    <input type="text" class="text" name="subject" placeholder="Subject" />
                  </div>
                </div>
                <div class="row half">
                  <div class="12u">
                    <textarea name="message" placeholder="Message"></textarea>
                    <!--Error message-->
                    <span class="error" id="err-message">please enter your message</span>
                   <!--End error message-->
                  </div>
                </div>
                <div class="row">
                  <div class="12u">
                    <input type="submit" class="button" value="Send Message" id="submit_btn" />
                    <div id="success"><h2>Your message has been sent. Thank you!</h2></div>
                  </div>
                </div>
              </div>
            </form>
          </article>

      </div>

and the PHP:

<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];

//Validate first
if(empty($name)||empty($email)||empty($message)) 
{
echo "Name and email and message are required!";
header('Location: index.html');
}
//validate against any email injection attempts
if(IsInjected($email))
{
echo "Bad email value!";
header('Location: index.html');
}


$msg =  " Name : $name \r\n"; 
$msg .= " Email: $email \r\n";
$msg .= " Message : ".stripslashes($_POST['message'])."\r\n\n";
$msg .= "User information \r\n"; 
$msg .= "User IP : ".$_SERVER["REMOTE_ADDR"]."\r\n"; 
$msg .= "Browser info : ".$_SERVER["HTTP_USER_AGENT"]."\r\n"; 
$msg .= "User come from : ".$_SERVER["SERVER_NAME"];

$recipient = "ashleynschneider29@gmail.com";  
$subject =  "Sender information";
$mailheaders = "From: $email\r\nReply-To: $email\r\nReturn-Path: $email\r\n";
$ok = mail($recipient, $subject, $msg, $mailheaders);

 if(isset($ok)){
header('Location: index.html'); 
 }else if(! isset($ok)){
echo "Name and email are required !";
 header('Location: index.html');
}


// Function to validate against any email injection attempts
function IsInjected($str)
{
  $injections = array('(\n+)',
          '(\r+)',
          '(\t+)',
          '(%0A+)',
          '(%0D+)',
          '(%08+)',
          '(%09+)'
          );
  $inject = join('|', $injections);
  $inject = "/$inject/i";
  if(preg_match($inject,$str))
{
    return true;
 }
  else
{
    return false;
 }
}
?>

Here's the Javascript too:

//---------------------------------- Forms validation -----------------------------------------//

/*click handler on the submit button*/
    $('#submit').click(function(){ 
        $('.error').fadeOut('slow'); 

        var error = false; 
        var name = $('input#name').val(); 
        if(name == "" || name == " ") {
            $('#err-name').fadeIn('slow'); 
            error = true; 
        }


            var msg = $('textarea#message').val(); 
            if(msg == "" || msg == " ") {
                $('#err-message').fadeIn('slow'); 
                error = true; 
            }

        var email_compare = /^([a-z0-9_.-]+)@([da-z.-]+).([a-z.]{2,6})$/; 
        var email = $('input#email').val(); 
        if (email == "" || email == " ") { 
            $('#err-email').fadeIn('slow'); 
            error = true;
        }else if (!email_compare.test(email)) { 
            $('#err-emailvld').fadeIn('slow'); 
            error = true;
        } 

        if(error == true) {
            return false;
        }

        var data_string = $('.contactForm').serialize(); 


        $.ajax({
            type: "POST",
            url: $('.contactForm').attr('action'),
            data: data_string,
            timeout: 6000,
            error: function(request,error) {
                if (error == "timeout") {
                    $('#err-timedout').fadeIn('slow');
                }
                else {
                    $('#err-state').fadeIn('slow');
                    $("#err-state").html('An error occurred: ' + error + '');
                }
            },
            success: function() {
                    $('#success').fadeIn('slow');
                        }
        });

        return false; 
    });

The one thing I found that will stop this is the way you are adding your php variables into your $msg variable.

You had: $msg = " Name : $name \r\n"; $msg .= " Email: $email \r\n";

try

$msg = " Name : ".$name." \r\n"; $msg .= " Email: ".$email." \r\n";

there were a few more in there, this is just an example.

Once I changed these I had a pretty clean run.

Hope this helps!

Alright! I think that helped! Thank you so much, I'm so new to all of this haha.

However, after changing the variables, I'm not getting the error message I used to, but it's not working as fluidly as I would like. Could it be my website host messing it up?

I guess that would all depend. Is it not responding well or long pauses? When troubleshooting these issues I will insert breakpoints in the code to see where the issues may happen. That will really help narrow down where it seems to starting acting less fluid.

Hope that makes sense to you.

It's responding and I'm getting the the test emails I send from the form, but I'm getting sent to a blank page upon hitting the submit button instead of getting the success h2. I will try breakpoints and see if that gets me anywhere.

Thanks for all your help!

I understand better now. Look into the callback property of the ajax function. That may solve your problem. I have not tested it with your code, but the ajax function is what is actually handling your post and can respond depending on returned values of send.php.

1 Answer

edit: replied to my own comment derp.