Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

WordPress

Maximiliane Quel
PLUS
Maximiliane Quel
Courses Plus Student 55,489 Points

AJAX Form in a Wordpress Page

Hi,

I have a Wordpress page that is build on Bootstrap and it has a contact form at the bottom of the page. I have tried setting up the form to be handled through AJAX but nothing seems to be working.

Here is the link to the site.

I am not sure how to proceed from here. Putting in a gravitas form has proved to be a styling nightmare. At the same time I am not sure how to get this form running. Do I need to create a plugin or is there something wrong with the AJAX request or PHP script?

I would really appreciate if someone can take a look and tell me what is wrong and/or how to get it up and running.

Thanks!

can you post any of your javascript / php handling code?

Maximiliane Quel
Maximiliane Quel
Courses Plus Student 55,489 Points

sure. I have the following code inside theme.js which is inside a js folder inside my theme directory:

jQuery(document).ready(function($) {

    var $feedbackContainer = $('#submitResult');

    $("#submit-btn").on('click', function(){

        var passedValidation = true;        
        //form validation

        //form handling
        if(passedValidation) {
            //create an object with input field data to be sent to server
            post_data = {
                'first_name'    : $('input[name=first-name]').val(), 
                'surname'       : $('input[name=surname]').val(), 
                'email'         : $('input[name=email]').val(), 
                'subject'       : $('input[name=subject-line]').val(), 
                'message'       : $('select[name=message]').val()
            };

            //AJAX for processing form
            $.post( 'js/engine/process_contactForm.php',
                    post_data,
                    function(response) {
                        //message text
                        $feedbackMessage = '<p>Show whether sending the form worked</p>';

                        $feedbackContainer.html($feebackMessage).removeClass('hidden');
                        $('#contactForm').hide();
                    }, //end of callback
                    'json'
            );

        } //end of form handlings       
    }); // end of submission event
}); // end of script

inside the js folder I have a folder called engine which holds a file called process_contactForm.php and has the following content:

<?php

if($_POST)

{
    $to_email       = "oxstew@gmail.com"; //Recipient email, Replace with own email here

    //check if its an ajax request, exit if not
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {

        $output = json_encode(array( //create JSON data
            'type'=>'error', 
            'text' => 'Sorry Request must be Ajax POST'
        ));
        die($output); //exit script outputting json data
    } 

    //Sanitize input data using PHP filter_var().
    $first_name     = filter_var($_POST["first_name"], FILTER_SANITIZE_STRING);
    $surname        = filter_var($_POST["surname"], FILTER_SANITIZE_STRING);
    $surname        = filter_var($_POST["surname"], FILTER_SANITIZE_STRING);    
    $email          = filter_var($_POST["email"], FILTER_SANITIZE_EMAIL);
    $subject        = filter_var($_POST["subject"], FILTER_SANITIZE_STRING);
    $message        = filter_var($_POST["message"], FILTER_SANITIZE_STRING);


    //additional php validation
    if(strlen($first_name)<2){ // If length is less than 2 it will output JSON error.
        $output = json_encode(array('type'=>'error', 'text' => 'First name is too short or empty!'));
        die($output);
    }
    if(strlen($surname)<2){ // If length is less than 2 it will output JSON error.
        $output = json_encode(array('type'=>'error', 'text' => 'Surname is too short or empty!'));
        die($output);
    }
    if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //email validation
        $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!'));
        die($output);
    }
    if(strlen($subject)<3){ //check emtpy subject
        $output = json_encode(array('type'=>'error', 'text' => 'Subject is required'));
        die($output);
    }
    if(strlen($message)<3){ //check emtpy message
        $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
        die($output);
    }

    //email body
    $message_body = "Regarding: ".$subject."\r\n".$message."\r\n\r\n-".$first_name." ".$surname."\r\nContact email : ".$email;

    //proceed with PHP email.
    $headers = 'From: '.$first_name."\s".$surname.'' . "\r\n" .
    'Reply-To: '.$email.'' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

    $send_mail = mail($to_email, $subject, $message_body, $headers);

    if(!$send_mail) {
        //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens)
        $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.'));
        die($output);
    } else {
        $output = json_encode(array('type'=>'message', 'text' => 'Hi '.$first_name.' Thank you for your email'));
        die($output);
    }
}

?>

let me know if that helps

1 Answer

Just discussed checking for $_POST === true recently with another student! watch out for this - $_POST might be empty and if it is, your code won't run. This means you'll miss out on any juicy validation potential. You could try checking the request method instead

<?php

 if ($_SERVER['REQUEST_METHOD'] === 'post') {
// witchcraft
}

With this check, you'll be 100% sure the code will always run when it gets a post request. If you want a none javascript fallback (which It looks like you're going to add? It looks like you'll only need to add the action and method to the html form attribute and call the same file ), checking the request method will work the same - and is almost more important because it's not going through the ajax validation.

Have you tried a suitable amount of alert("got to here"); / echo $variable; exit; and if so, how far does the script get?

Maximiliane Quel
Maximiliane Quel
Courses Plus Student 55,489 Points

I changed the condition at the top of the php file as you suggested. It's still completely dead. I'm not sure how to do that kind of testing. I'm sorry. Form handling seems to be my Achilles heel. Before I put in the form processing the AJAX request had a callback that would only display a static error message and hide the button when it was pressed. That worked fine, but since I put it all together it doesn't do anything

No worries, so start of nice and simple (this will work as long as there's no syntax errors. I checked your javascript with firebug and it's looking okay so this should work).

Start off really simple. Place an alert function e.g. alert("AJAX Called"); or similar at the top of the anonymous click function for the form submission.. Does that work?

when i click the button whilst checking for errors in firebug i get:

"NetworkError: 404 Not Found - http://carboueres.com/js/engine/process_contactForm.php"

does that point to the right place?

Maximiliane Quel
Maximiliane Quel
Courses Plus Student 55,489 Points

the process_contactForm.php is inside the theme directory in the js folder in an engine folder so the pass should probably look like this:

http://carboueres.com/wp-content/themes/js/engine/process_contactForm.php

since the js file is in a folder just one level up I thought by putting in the relative path it should find the right file though. I moved the file into the same folder as the js file and that didn't seem to work either. so I have now put in the absolute path to the php processing file. still doesn't seem to work for me

Maximiliane Quel
Maximiliane Quel
Courses Plus Student 55,489 Points

now I get the following error in the console: Uncaught ReferenceError: $feebackMessage is not defined

Maximiliane Quel
Maximiliane Quel
Courses Plus Student 55,489 Points

I found a typo. it worked. now going to see if it works when put it in empty.

nice!

Maximiliane Quel
Maximiliane Quel
Courses Plus Student 55,489 Points

thanks very much for being a great help and an awesome sounding board. still a bit left to do. hope nothing goes wrong from here.

No worries! I only looked at firebug :p I find (as I'm sure most developers do) that regular alerts, var_dumps and echo's get you through most bugs. If none of them show up/work it's likely there's a syntax error, file path error or a call to a function that doesn't exist. Those would be my most common mistakes!

Good luck with it, it looks awesome.

Maximiliane Quel
Maximiliane Quel
Courses Plus Student 55,489 Points

thanks :0). I think putting in alerts, echos and the like is a really good tip. just looking helped a lot!!