Help with php form

HI guys, I’m new to the forum and to php as well, in the sense that I don’t have any real and solid php coding experience, I’ve only “played” with it a few times.
Now, I have to build this php form and, considering the lack of knowledge I think I’ve done OK so far, but there are a few obstacles that I don’t seem to be able to overcome alone.
So, before posting the code, here is what I’m supposed to build:
-An HTML contact form that has php validation and that upon submission emails the content to an email address
I’ve done a bit of reading, looked at quite a few tutorials and although not everything is clear I do have some other programming experience plus HTML and CSS so hopefully it won’t be hard.
I’ve built the form, even done the validation (it seems to work) and the submission with the email, but here are the things that I couldn’t get to work:
1)I have a title field with a few options (first option is “Please select”) and when I select one of them and press the submit button,if the form contains an error and reloads, the option selected in the title field reverts back to the default “Please select”: how do I make sure that the selected option remains selected throughout the process?
2)When I click submit the page jumps up to the top. That’s expected behaviour of course but I can’t use a e.preventDefault() in jquery otherwise the form won’t submit, is there any way in php to stop the page jumping up when the form is submitted? Ideally, what I’d like is to display a thank you message when the form has been submitted
3)Once the submission has occurred, the data typed in the form is still there: shouldn’t that disappear automatically?
4)the email I receive after the form has been submitted isn’t properly formatted in the sense that everything runs on the same line even if I’ve used “/r/n”.
So, here is the form with the php script and if you want to see it in action here is the link to the site (just click get in touch and you’ll see the form http://antonioborrillo.co.uk/agency_test/test/en/index.php)

[php]

<?php //create variables for validation $titleError = ""; $firstNameError = ""; $lastNameError = ""; $emailAddressError = ""; $messageError = ""; $websiteError = ""; $titleError = ""; $title = ""; $firstName = ""; $lastName = ""; $emailAddress = ""; $message = ""; $website = ""; //mail variables $to = "[email protected]"; $subject = "New request"; $currentTitle = $_POST["title"]; $currentMessage .= "Title: " . $_POST["title"] . "\r\n"; $currentMessage = "First Name: " . $_POST["firstName"] . "\r\n"; $currentMessage .= "Last Name: " . $_POST["lastName"] . "\r\n"; $currentMessage .= "Email address: " . $_POST["emailAddress"] . "\r\n"; $currentMessage .= "Website: " . $_POST["website"] . "\r\n"; $currentMessage .= "Message: " . $_POST["message"] . "\r\n"; //keep track of how many errors $errors = 0; $headers = 'MIME-Version: 1.0' . "\r\n"; $headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n"; //mail($to,$subject,$currentMessage,$headers); if($_SERVER["REQUEST_METHOD"] == "POST"){//has the form been submitted? //validate title if($_POST["title"] == "0"){ $titleError = "Select a title"; $errors = 1; } else{ $title = $_POST["title"]; $errors = 0; } /* if( 0 != $_POST['title'] ) { $title = $_POST['title']; } else { $titleError = "required"; } */ //validate firstName if (empty($_POST["firstName"])){//if empty $firstNameError = "First name is required"; $errors = 1; } else{ $firstName = test_input($_POST["firstName"]); // check if firstName only contains letters and whitespace if(!preg_match("/^[a-zA-Z ]*$/",$firstName)){ $firstNameError = "Only letters and white space allowed"; $errors = 1; } else{ $errors = 0; } } if (empty($_POST["lastName"])){//if empty $lastNameError = "Last name is required"; $errors = 1; } else{ $lastName = test_input($_POST["lastName"]); // check if lastName only contains letters and whitespace if(!preg_match("/^[a-zA-Z ]*$/",$lastNameError)){ $lastNameError = "Only letters and white space allowed"; $errors = 1; } else{ $errors = 0; } } if(empty($_POST["emailAddress"])){ $emailAddressError = "Email is required"; $errors = 1; } else{ $emailAddress = test_input($_POST["emailAddress"]); // check if e-mail address is well-formed if(!filter_var($emailAddress, FILTER_VALIDATE_EMAIL)){ $emailAddressError = "Invalid email format"; $errors = 1; } else{ $errors = 0; } } if(empty($_POST["website"])){ $website = ""; $errors = 0; } else{ $website = test_input($_POST["website"]); // check if URL address syntax is valid (this regular expression also allows dashes in the URL) if(!preg_match("/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$website)) { $websiteError = "Invalid URL"; $errors = 1; } else{ $errors = 0; } } if(empty($_POST["message"])){ $messageError = "Message required"; $errors = 1; } else{ $message = test_input($_POST["message"]); $errors = 0; } if($errors == 0){ mail($to,$subject,$currentMessage,$headers); } /* else{ return false; } */ } function test_input($data){ $data = trim($data); $data = stripslashes($data); $data = htmlspecialchars($data); return $data; } ?>

[/php]

<div class="pseudoPage contact" data-item="contact">
				<h2>Contact us</h2>	
					<p>We're always excited to work on a new project, so give us a shout!</p>
					<p>Fill in the form or drop us a line at <a href="mailto:[email protected]">[email protected]</a></p>
				<div class="contactForm">					
					<div class="contactFormPanel">	
						<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
							<div class="control-group">
								<label class="control-label" for="title">Title*</label>
								<div class="controls">
									<select id="title" name="title">
										<option value="0">Please select</option>
										<option value="1">Mr </option>
										<option value="2">Mrs</option>
										<option value="3">Ms</option>
										<option value="4">Sir</option>
									</select>
									<span class="error"><?php echo $titleError;?></span>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label" for="firstName">First name*</label>
								<div class="controls">
									<input id="firstName" type="text" name="firstName" value="<?php echo $firstName;?>">
									<span class="error"><?php echo $firstNameError;?></span>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label" for="lastName">Last name*</label>
								<div class="controls">
									<input id="lastName" type="text" name="lastName" value="<?php echo $lastName;?>">
									<span class="error"><?php echo $lastNameError;?></span>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label" for="emailAddress">Email address*</label>
								<div class="controls">
									<input id="emailAddress" type="text" name="emailAddress" value="<?php echo $emailAddress;?>">
									<span class="error"><?php echo $emailAddressError;?></span>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label" for="website">Website</label>
								<div class="controls">
									<input id="website" type="text" name="website" value="<?php echo $website;?>">
									<span class="error"><?php echo $websiteError;?></span>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label" for="message">Enter your message*</label>
								<div class="controls">
									<textarea id="message" name="message"><?php echo $message;?></textarea>
									<span class="error"><?php echo $messageError;?></span>
								</div>
							</div>							
							<div class="control-group">
								<div class="controls">
									<div class="button">
										<!-- <a href="#">Submit</a> -->
										<input type="submit" name="submit" value="Submit">
									</div>
								</div>
							</div>
							
						</form>
					</div>
				</div>
				
			</div>

What I would be extremely grateful is that if somebody can have a quick glance at the code and help me out with the above issues. If it turns out that what I’ve done is rubbish, then I’m more than happy to re-write the whole thing but I’ll need some help getting it right

You need to echo the selected value, like you do for the other form fields.

If you catch the form submit event and prevents the default action it won’t submit, no. What you can do (and is often done), is to preventDefault, and submit the form using ajax. Then the form submit request will not refresh the page and you will not “jump to the top” afterwards.

PHP will set the form fields to whatever you echo in the field values. So on a successful submit you could send the email and reset the form (set all values to null).

the mail function is pretty bad, I strongly advise you try to use PHPMailer instead

Thanks for looking at the code.
You need to echo the selected value, like you do for the other form fields.
Sure, but how do I do that with a select tag? For the other ones it was pretty obvious, in the sense that you just add a php tag as the value
but in the select tag I don’t see any obvious way. I mean if I create a variable
[php]$title = $_POST[“title”];[/php]
which will, presumably get the value of the selected option, where do I then add it within the select, as a value of which option?
Do I replace the current one with the new one, something like this:
[php]
Please select
Mr
Mrs
Ms
Sir
[/php]
If so then I will have to reset it again once the form is submitted?

PHP will set the form fields to whatever you echo in the field values. So on a successful submit you could send the email and reset the form (set all values to null).
OK cool thanks. Can I create a resetField function that does the job? In terms of resetting the actual fields, I had a look around and found a few ways (not sure if they are reliable though).
This:
[php]function reset_fields(){
$_POST = array();
}[/php]
or this
[php]function reset_fields(){
$(".myform")[0].reset();
}[/php]
Would any of these do?

the mail function is pretty bad, I strongly advise you try to use PHPMailer instead

OK no worries I don’t mind using that, but just out of interest,are you saying that the current one is pretty bad because it is not safe and could cause security risks?

What you can do (and is often done), is to preventDefault, and submit the form using ajax
OK, I’ve only used ajax a couple of times, I will need a refresher course on it, will look online as to how to submit a form with ajax

In view of all the changes above, how do you suggest I prooceed? What do you reckon I should do first? Is it easier to scrap everything and start from srcatch or can I keep something like, say, the validation?
You didn’t say anything aboutt he validation so I suppose that’s OK as it is?
thanks for your help

HTML selected Attribute
http://www.w3schools.com/tags/att_option_selected.asp

It depends on how you use the the form in your code. You set local variables (like $title) from the $_POST array, which you then display in your template/view. So resetting $_POST will not do anything in this case.

PS: the last one is javascript

It’s not configurable, it doesn’t have any features except the bare basics, it doesn’t have any error reporting (!!), etc.

Just continue working on it, no matter what you end up with now you will want to rewrite it next month. That’s one of the “joys of programming” ^^

OK thanks.

OK I see, thanks for the hint. I think I sorted that out by doing this:
[php]$title = $_POST[“title”];


<option <?php if($title == 0) echo 'selected'; ?> value=“0”>Please select
<option <?php if($title == 1) echo 'selected' ?> value=“1”>Mr
<option <?php if($title == 2) echo 'selected' ?> value=“2”>Mrs
<option <?php if($title == 3) echo 'selected' ?> value=“3”>Ms
<option <?php if($title == 4) echo 'selected' ?> value=“4”>Sir
[/php]

So do I have to reset them manually instead, something like:
[php]function reset_fields(){
$title = “”;
$firstName = “”;
$lastName = “”;
$emailAddress = “”;
$message = “”;
$website = “”;
}[/php]

Being really new to PHP, I don’t think I need any of that because all I need is a quick and dirty solution to get emails when somebody submits a form, so perhaps I could work with that. A textual email is more than enough for me, sure I might need to get a proper email as a sender and sort out the layout slightly

Finally about the ajax business, it seems that is the way to go. I’m doing a bit of reading now, but can I get some help with that here in this forum as well?

Problem is when the script doesn’t send an email and all you get returned from the mail function is “false”. You have no way of figuring out what’s wrong.

Yes, no problem. There’s an entire sub forum dedicated to it :slight_smile:

Sending email, verifying passwords and other security issues I rather have a library or a built-in function handle it than trying to create it myself. Don’t get me wrong I used to think heck it’s only email I just write the script myself and it’ll be easier. While technically easier (after you get the knack of writing it), it’s safer to use a library (such as PHPMailer) to do the email portion of the script. It’s a little more secure than writing it yourself, you don’t have write you own email routine (I’m talking about the core of it) every time thus saving you time and you get the bonus of sending HTML (Though there a still people who get a little squeamish when the receive HTML emails). Just my opinion.

I honestly don’t think that should be our problem. My email client is set up to show the plain text content, with the html version attached.

OK that’s fine, like I said I’m happy to go for the solution you suggested, and perhaps it’s for the best anyway since I don’t know much PHP.
However, would it be good to leave this as a last thing as I’d like to sort out the ajax side of things first. How easy is to then combine PHP mailer with the result of the ajax call and move on with the processing (ie sending the email as I suppose the validation has already taken place at this point)?
Also, sorry what about that clearing the fields after submission? Sorry I’m still not 100% clear on that. [member=71845]JimL[/member], would this be a solution you think, or do you know a better way?
[php] function reset_fields(){
$title = “”;
$firstName = “”;
$lastName = “”;
$emailAddress = “”;
$message = “”;
$website = “”;
}
[/php]
Thanks

You should be aware of scopes when using functions

[php]$foo = 1;
// $baz is not available here

function someFunction() {
// $foo is not available here
$baz = 2;
}

// $baz is not available here[/php]

Ah OK! I thought that I declared the variable as global as therefore I could change them from anywhere. Maybe it works differently in PHP then. OK so I’ll pass them as parameters to the function then

Globals are evil. ^^

Sponsor our Newsletter | Privacy Policy | Terms of Service