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

Ana Camelo
PLUS
Ana Camelo
Courses Plus Student 13,218 Points

Contact Form - jQuery/PHP

Hello,

I was trying to create a contact form for a website using as a model the one you use in Form Validation/Manipulation - Build an Interactive Website, but even doing everything as it it is in the example files it doesn't seem to work ok.

In this part of the code, it is not quite clear to me why do we have "contact.php" if for what I understand it is a link to go after sending the form:

<p>form action="contact.php" method="post"</p>

Also, I don't understand well how do I link the php file to the HMTL markup.

And finally, I'm going to be using 3 forms along the complete site:

  1. Only to enter an email address in the footer
  2. A FAQ form
  3. A contact form

When using jQuery, in order to validate each form, how do I link the code to an specific form. For instance, in the contact page I'll have the contact form and also need to validate the footer form. How can I make this all work?

Thanks a lot!

8 Answers

Jim Hill
Jim Hill
1,758 Points

Aha - that is because you are simply clicking on the file and not requesting it via an URL.

You need to be running the files via a web server to access the javascript. (See this bit: file://localhost// ? I would become http://localhost if you were serving the file from a web server). The bit before the two forward slashes is called the protocol. To view websites you will use either http or https (secure http).

Your browser will not allow JavaScript to run if you simply open up the file by double-clicking on it. This would be a big security risk as it would simple to get people to click on a file and run malicious code. It's called a Security Sandbox.

You need to go to your browser and enter manually in the address bar: http://localhost

(this is assuming you have set up a web server running on localhost as otherwise you won't be running your PHP either!).

That should help ;)

Jim Hill
Jim Hill
1,758 Points

I have not see the tutorial but as an overview:

<form action="contact.php" method="post"> will send a form submission to the url contact.php

You will then process the POST variables in your contact.php script.

In jQuery the two simplest ways of targeting elements in the HTML (we refer to the whole make up of the HTML in the page as the DOM) are using element 'classes' and element 'ID's. So as an example:

<p id="myParagraphId" class="myParagraphClass">Some text</p>

To do things to this paragraph we can target it using it's id and a hash symbol $('#myParagraphId') or it's class and a dot symbol $('.myParagraphClass'). There are lots of reasons to use either a class or ID but that is another subject. Without going into too much detail and confusing things, generally we would use classes far more often that IDs.

For more information look at: https://learn.jquery.com/using-jquery-core/faq/how-do-i-select-an-item-using-class-or-id/

Ana Camelo
PLUS
Ana Camelo
Courses Plus Student 13,218 Points

Thanks a lot!

I understand how to target form elements with jQuery, but for some reason it seems that none of the jQuery I have at the bottom of mi script works, so I tried and copied and pasted everything as it was on the example files, but it does't work anyways. All if the inputs/text areas are working with id.

I just don't understand why it doesn't work.

About the <form action="contact.php" method="post">

When I work on the example files, as soon as I click on submit, it sends me to the php file. I reviewed all HTML about this and it says so, the link you have there is the target link to go after submitting the form. I think I got a bit more confused :/

Jim Hill
Jim Hill
1,758 Points

Are you using a developer inspector e.g. the Developer Tools in Chrome? This will show you if your JavaScript has errors in it. If your JavaScript has errors in it then it will not run. When developing with JavaScript for the browser it's worth getting cosy with the console in your Developer Toolbar ;)

The form submission is supposed to take you to the target URL? That's the way it is designed to work. It sends you to the page along with a bunch of variables that you have entered in the form. Then on the page that you land on you can then process the variables and decide what you want to do after (render a page, redirect the user, send an email etc).

It's probably worth a spot of learning on how HTTP headers actually work: http://net.tutsplus.com/tutorials/other/http-headers-for-dummies/ Most modern web frameworks in nearly all languages are based around the way http requests work so it is a good idea to learn what they are (it's how web pages work essentially).

Ana Camelo
PLUS
Ana Camelo
Courses Plus Student 13,218 Points

I didn't remember about the console, but you are right it show this error messages

Failed to load resource file://localhost//MVG%20Co%203/js/jquery.js Uncaught ReferenceError: $ is not defined

So, about the target URL if it is taking me to the php file as it is, how do I do to take it to another page or just refresh the actual page containing the for? Should i do that on the php file then?

Thanks again!

Ana Camelo
PLUS
Ana Camelo
Courses Plus Student 13,218 Points

It finally worked!!! Thanks a looot!!

Sorry if I'm too annoying, i just have 2 more questions:

In the jQuery script I have it as all files are required otherwise the submit button won't work. I want it to be that way. However, now testing it it is still disabled when all fields are completed and valid.

This is the jQuery I have

´´´ jQuery var $submit = $(".submit input"); var $required = $(".required"); function containsBlanks(){ var blanks = $required.map(function(){ return $(this).val() == "";}); return $.inArray(true, blanks) != -1; }

        function isValidEmail(email){
            return email.indexOf("@") != -1;
        }

        function requiredFilledIn(){
            if(containsBlanks() || !isValidEmail($("#email").val())) 
                $submit.attr("disabled","disabled");
            else 
                $submit.removeAttr("disabled");
        }

        $("#form span").hide();
        $("input,textarea").focus(function(){
            $(this).next().fadeIn("slow");
        }).blur(function(){
            $(this).next().fadeOut("slow");
        }).keyup(function(){
            //Check all required fields.
            requiredFilledIn();
        });

        $("#email").keyup(function(){
            //Check for a valid email.
            if(isValidEmail($(this).val()))
             $(this).next().removeClass("error").addClass("valid");
            else 
             $(this).next().removeClass("valid").addClass("error");
        });

        requiredFilledIn();
  1. One of the forms I'm using is in the footer and it just to send an email address, so, instead of writing all the validation script, may I change the #email to .email? Or should I write it again with a different ID since they are in the same page (both forms)? I'll have to create another form in another page of the site, so same question, can I use the same jQuery script and just change the ID names or the same one would work?
Jim Hill
Jim Hill
1,758 Points

I'll get you to debug your code as it is better practice. So as a guide try using the console to see where your errors are coming from e.g.:

function requiredFilledIn() {
    if (containsBlanks() || !isValidEmail($("#email").val())) {
        console.log('Should be disabled');
        $submit.attr("disabled", "disabled");
    } else {
        console.log('Should be enabled');
        $submit.removeAttr("disabled");
    }
}

Don't forget to remove your console debugging from the final production code!

As for question 2 you should only define an ID once per page in HTML unlike classes which can be used on unlimited elements. So you could you reference a target in jQuery for email validation like $('form .email') which means "all elements in the DOM with a class of 'email' that are children of a form element"

Ana Camelo
PLUS
Ana Camelo
Courses Plus Student 13,218 Points

Thanks a lot!! It did work very well!! When I click on either, they both take me to the .php file, which I suppose is what is meant to do so far.

For the one that is in the footer, I still have a question: In the .php file there's this line

    header("location: contacto.html");

In this case, it is indeed in the page it says, but what if I want to copy that code into the other site pages? What will be the result of that? Will it still work ok?

thanks a lot!