Menu icon Foundation
Which system is best to make e-mail contact form work in Foundation 5?

Hello

I want to use an e-mail contact form on my Foundation 5 website, but I know absolutely zero about how to do it.

Could anyone please let me know which system is the best one to use in order to get an e-mail contact form to work? I have found some tutorials about using AJAX, PHP and jQuery, so I was wondering if that method would be suitable.

Also, is jQuery made available on all Foundation 5 pages by default? I have some script references on my page, but I don't know what they actually do (please see attached code below). I think one of them might make all the scripts available from the library, but I don't know which one that is, nor how it actually does that. If jQuery is available on my page, how do i call it to actually work?

The tutorials I have looked at show code in the head section of the page, but mine is at the bottom of the main page body. Is this the same thing, or do I need to put something in the head section of my page as well?

Thanks very much in advance.

<!-- This is in the head section of my page -->

<script src="bower_components/modernizr/modernizr.js"></script>




<!--This is at the bottom of my page, just before the closing body tag -->

<script src="bower_components/jquery/dist/jquery.min.js"></script>
    <script src="bower_components/foundation/js/foundation.min.js"></script>
    <script src="js/app.js"></script>
  
            

         

e-mailemailcontact formFoundation 5jqueryAJAXPHP

Hello

I want to use an e-mail contact form on my Foundation 5 website, but I know absolutely zero about how to do it.

Could anyone please let me know which system is the best one to use in order to get an e-mail contact form to work? I have found some tutorials about using AJAX, PHP and jQuery, so I was wondering if that method would be suitable.

Also, is jQuery made available on all Foundation 5 pages by default? I have some script references on my page, but I don't know what they actually do (please see attached code below). I think one of them might make all the scripts available from the library, but I don't know which one that is, nor how it actually does that. If jQuery is available on my page, how do i call it to actually work?

The tutorials I have looked at show code in the head section of the page, but mine is at the bottom of the main page body. Is this the same thing, or do I need to put something in the head section of my page as well?

Thanks very much in advance.

<!-- This is in the head section of my page -->

<script src="bower_components/modernizr/modernizr.js"></script>




<!--This is at the bottom of my page, just before the closing body tag -->

<script src="bower_components/jquery/dist/jquery.min.js"></script>
    <script src="bower_components/foundation/js/foundation.min.js"></script>
    <script src="js/app.js"></script>
  
            

         
Michael about 5 years ago

I forgot to add, this is the tutorial I am looking at:

http://www.hongkiat.com/blog/ajax-html5-css3-contact-form-tutorial/

Is that suitable for what I want to do?

I have also found this one, which I was wondering if it might be better as it is more recent:

http://blog.teamtreehouse.com/create-ajax-contact-form

Thanks very much.

Darek Wędrychowski about 5 years ago

JQuery is available by default, you just need to include it in your main template. The way to do that is explained here: http://foundation.zurb.com/docs/javascript.html

But you don't need to use JQuery or Ajax to make a simple contact form working. PHP is fine, but do I understand it correctly that right now you're making your page only in HTML, without a backend?

Michael about 5 years ago

Hello, and thank you for your reply.

Yes, my website is just HTML. I am using the Foundation 5 template and I have it set up so I can edit _settings.scss, and also add my custom CSS to the bottom of the app.scss file.

Apart from displaying text and image files, the only other functionality I need for site visitors is the contact form and a slideshow. I also want to use Sharrre media buttons, but I had to give up on that for now as I couldn't find anything that related to getting it to work with Foundation websites.

I would like to have some sort of contact management system for it when it is finished, but I know nothing about that yet. I have looked at WordPress as a platform, and went as far as setting up WampServer with WordPress, but I will return to that and learn more when I have the site finished.

I don't mind spending the time to learn the necessary technology to create the contact form, but the problem is that I'm absolutely clueless at the moment, with no understanding of the overall concept, or what thing performs which function, and why! After some reading I have a vague idea about where PHP is used (and why), along with how CSS and HTML is tied into the whole thing, but AJAX only ever seems to get mentioned as if it appears magically, as a result of other things being used. I understand what it stands for, and what it allows you to do, but it's very unclear to me in what way it exists in such a capacity that it can then be employed to actually do something.

Thank you for the link. I will read that and hopefully learn a bit more! I didn't know that this could all be done without AJAX and jQuery.

Darek Wędrychowski almost 5 years ago

The only reason you'd want to use Ajax for a contact form would be if you didn't want the page to reload after sending the form (to make it work in the background). As much as it may looks nice, it isn't necessary in your case, as after sending the form your user won't care what happens anyways - he already achieved what he wanted to do. So you just need a simple PHP file for that, that could take care of sending the email.

But the provided code examples are easy so you may do it Ajax way if you prefer. The code is practically ready to use, so you can make it working very fast and you don't actually need to understand the background of Ajax for that. Personally, I'd go with the second link, as I think it will b easier to read and understand for you - http://blog.teamtreehouse.com/create-ajax-contact-form

Still, you may want to change it a bit, so the copy of the message is sent also to its author (it can be also optional). This will help him remember what he wrote and that he actually wrote something. If you go this way, you may want to make your PHP script safe against possible spam. On the other hand the spam protection would require saving some data either in the file or in a database, so it's another thing to learn for a small feature.

Take in mind that nowadays less and less people write pages in pure PHP, the most common way to do that is to use one of PHP frameworks (like Foundation is a CSS framework). The same with Ajax - it's the recent trend to use Javascript frameworks like Angular (the one used in Foundation for Apps, but it works perfectly with Foundation 5 too).

In your case, the website doesn't need it, as the contact form feature is very simple and small, also you've already got a nice tutorial you can use.

If you happen to have any problems with the script, feel free to include the code here so I can take a look and help you.

Michael almost 5 years ago

Thank you!

Your explanation is very helpful, and it has given me a good starting point for how to approach this task.

It is beginning to make sense now!

Michael almost 5 years ago

I have got my contact form working, apart from a couple of things. I can't get it to display any success or error messages on the actual website page.

When trying to force error messages (just as a test to make sure they work) by entering nothing in the fields and pressing the 'send' button, I don't get any error messages appearing in their dedicated div section placed above the form's HTML.

When I send an e-mail using WampServer and Test Mail Server Tool, it sends the e-mail to the program's mailbox, but the success message ('Thank you. Your message has been sent.') is displayed on a separate white page, rather than on my contact form page. The address of this page is http://my-project-name-here/mailer.php. The same happens for the error message if I force an error by trying to send an e-mail without the Test Mail Server Tool running. It displays the error message ('Oops! Something went wrong and we couldn't send your message.') at the same page location as above (mailer.php).

I'm not really sure where to look for problems. Is there anywhere specific that I can check for errors? I had a look in Firefox by going to Inspect Element, and then Debugger, and for the 'foundation.min.js script it said 'This source is blackboxed. Its breakpoints are disabled, and stepping skips through it.'. I've no idea if this is anything to do with the problem. The other two scripts shown were jquery.js and modernizr.js, which I could view, but I've no idea what to do with them.

The Apache error log and PHP error log in WampServer aren't showing anything. I can't see anything relevant with regard to error messages in Windows Event Viewer. My javascript and PHP script are straight out of the tutorial, so I don't think I have caused any problems there.

Here is my javascript file, which is in my app.js file:

// Foundation JavaScript
// Documentation can be found at: http://foundation.zurb.com/docs
$(document).foundation();



//This is for the contact form.

$(function() {

  // Get the form.
  var form = $('#ajax-contact');

  // Get the messages div.
  var formMessages = $('#form-messages');

  // Set up an event listener for the contact form.
  $(form).submit(function(e) {
    // Stop the browser from submitting the form.
    e.preventDefault();

    // Serialize the form data.
    var formData = $(form).serialize();

    // Submit the form using AJAX.
    $.ajax({
      type: 'POST',
      url: $(form).attr('action'),
      data: formData
    })
    .done(function(response) {
      // Make sure that the formMessages div has the 'success' class.
      $(formMessages).removeClass('error');
      $(formMessages).addClass('success');

      // Set the message text.
      $(formMessages).text(response);

      // Clear the form.
      $('#name').val('');
      $('#email').val('');
      $('#message').val('');
    })
    .fail(function(data) {
      // Make sure that the formMessages div has the 'error' class.
      $(formMessages).removeClass('success');
      $(formMessages).addClass('error');

      // Set the message text.
      if (data.responseText !== '') {
        $(formMessages).text(data.responseText);
      } else {
        $(formMessages).text('Oops! An error occured and your message could not be sent.');
      }
    });

  });

});

Here is my PHP script, which is saved to its own file and placed in my main project folder along with the HTML pages:

<?php

    // Only process POST reqeusts.
    if ($_SERVER["REQUEST_METHOD"] == "POST") {
        // Get the form fields and remove whitespace.
        $name = strip_tags(trim($_POST["name"]));
        $name = str_replace(array("\r","\n"),array(" "," "),$name);
        $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
        $message = trim($_POST["message"]);

        // Check that data was sent to the mailer.
        if ( empty($name) OR empty($message) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
            // Set a 400 (bad request) response code and exit.
            http_response_code(400);
            echo "Oops! There was a problem with your submission. Please complete the form and try again.";
            exit;
        }

        // Set the recipient email address.
        // FIXME: Update this to your desired email address.
        $recipient = "[email protected]";

        // Set the email subject.
        $subject = "Enquiry from $name";

        // Build the email content.
        $email_content = "Name: $name\n";
        $email_content .= "Email: $email\n\n";
        $email_content .= "Message:\n$message\n";

        // Build the email headers.
        $email_headers = "From: $name <$email>";

        // Send the email.
        if (mail($recipient, $subject, $email_content, $email_headers)) {
            // Set a 200 (okay) response code.
            http_response_code(200);
            echo "Thank You. Your message has been sent.";
        } else {
            // Set a 500 (internal server error) response code.
            http_response_code(500);
            echo "Oops! Something went wrong and we couldn't send your message.";
        }

    } else {
        // Not a POST request, set a 403 (forbidden) response code.
        http_response_code(403);
        echo "There was a problem with your submission.  Please try again.";
    }

?>

Here is the HTML for the form, which forms part of my page. I have split the form across two columns, and above this is a full-width div containing the div for the error and success messages (which doesn't seem to work!):

  <div class="large-12 medium-12 small-12 columns justify success error"> <!-- Special div for form error and success messages -->

        <div id="form-messages"></div>  

      </div>



          <div class="large-4 medium-5 small-12 columns"> <!-- Left-hand column for contact name and e-mail address boxes -->


                    <form id="ajax-contact" method="post" action="mailer.php"> <!-- Opening form tag in left-hand column-->
                        <div class="field">
                            <label for="name">Name:</label>
                            <input type="text" id="name" name="name" required>
                        </div>

                        <div class="field">
                            <label for="email">Email:</label>
                            <input type="email" id="email" name="email" required>
                        </div>


          </div> <!-- Closing tag for left-hand column -->



          <div class="large-8 medium-7 small-12 columns"> <!-- Right-hand column for message text box and send button -->


                        <div class="field">
                            <label for="message">Message:</label>
                            <textarea class="contact-message-height" id="message" name="message" required></textarea>
                        </div>

                        <div class="field">
                            <button class="button small contact-button-width" type="submit">Send</button>
                        </div>
                    </form> <!-- Closing form tag in right-hand column -->


          </div> <!-- Closing tag for right-hand column --> 

Michael almost 5 years ago

I have tried moving the 'class="success error"', but that didn't work. I put it in the innder div, the outer one that defines the columns, a further experimental outer div containing the two previous ones, and in a div without an outer column-container div. None of those worked.

I also tried putting style="visibility:hidden;">[file upload] between two paragraph tags as that was suggested for a similar problem on a WordPress forum thread. That didn't work. I also tried the same but with the success and error div class added to the paragraph tags.

On the JSFiddle site I put the mailer script onto the page to test it and it said it was okay.

EDIT: I installed Firebug and tried that. The only thing it comes up with for errors is this:

"The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol."

But that is for the PHP success message page that is loading (the one I don't want!).

I wonder if this is something I am doing wrong with my HTML. If no errors are apparent in Firebug, then would that mean it's likely to be a problem with what I have done with the HTML? I have tried moving the the error and success class around, as described above, but I don't know what else to try.

Michael almost 5 years ago

I have made some progress, although it is still not working, and I'm not sure what I've actually achieved.

From reading about other people's AJAX problems on WordPress-related forums, where error and success messages didn't work, one person said they got theirs working by going back to a previous version of jQuery.

My Bower Components folder has a jquery.min.js file with a version of 2.1.1, so I copied an earlier version (1.11.2) from the jQuery website and pasted it into my app.js file, above my contact form script.

Now, when I fill in my contact form to test it, and press 'send', I get the contents of my PHP file appearing on my contact page, in the correct place for the error or success messages - i.e. above the contact form, where the error/success div is located.

It is sending the e-mail (as that appears in my Test Mail Server Tool folder), and it is now returning data to the correct place on my page. The problem now is that the returned data is the whole contents of my mailer.php file, rather than a success or error (in this case, success) message.

I presume that this indicates some sort of problem with using the Foundation jQuery 2.1.1 file, as that didn't result in anything appearing in my error/success div. There is obviously still a problem, but a lesser problem, as I now only need to get the contents of the error/success div to display an appropriate message, rather than the whole contents of mailer.php.

Could anyone possibly suggest something else to try?

Thanks very much in advance.

Michael almost 5 years ago

UPDATE: I've got it working! I'm just posting here in case this is of help to anyone else.

Having replaced my version 2.1.1 jQuery file that didn't work, with version 1.11.2 that nearly worked (see post above), I thought I would try an even earlier version. I found a copy of version 1.10.1 and pasted that into my app.js file, above my contact form, then tried the form, and the success message appeared correctly above my form.

So, it appears to be the version of jQuery in Foundation 5 that was causing the problem - or perhaps you could say that my contact form was causing a problem with the Foundation 5 jQuery file!

I presume that pasting the earlier version of jQuery into my app.js file is the correct way to do it. Is this simply overriding the later version that is still in my bower_components/jquery/dist folder? Is this earlier version likely to cause problems anywhere else in Foundation? I can't see anything else on my pages malfunctioning with this version 1.10.1.

olidev about 1 year ago

I think PHP, MySQL, and AJAX jQuery combination is perfect to create a contact form in Foundation. Most of the websites use this system. This type of PHP contact form is easy to create as well. You can easily add email method in it. 

François Marie Arouet Voltaire about 1 year ago

Hi! Actually, choosing a form depends on your purposes. I mean, as far as all such platforms offer different tools and services it's difficult to decide finally. Personally, I prefer non-email but more convenient services. This https://aidaform.com/, for instance. Dunno, maybe I should just get used to emails but for now only the platform I mentioned earlier.