MillerMedia
MillerMedia

Reputation: 3671

Trouble Validating Required Text in textarea with PHP/MySQL

I have a textarea that I am trying to validate whether someone has filled out or not before submitted the form. I'm doing all of my validation server side with PHP.

I had two thoughts. Either:

1) submit the form to itself and have the fields validate themselves on the same page and then redirect to the page where the form would update my database. The problem I had was that since it was posting to itself, once the page redirected, I couldn't carry out using the POST values because they were no longer valid.

2) So I figured I'd just do the validation on the second page (the page that the form initially is set to post to). Here's my code for that page, where 'description' is the name of the textarea:

session_start();
if(!$_POST['description']){
echo "<script>alert(\"Please fill out all fields\");</script>";
header("location:post_job.php");
}

And then it redirects back to the page where the form is being filled. I get this error though:

Warning: Cannot modify header information - headers already sent by (output started at siteinfo/site/checkjob.php:4) in siteinfo/site/checkjob.php on line 5

Line five is the header line (so line four is obviously the echo line). I don't understand why it would create that error since I haven't sent a header yet. Any help would be greatly appreciated. Thanks!

Upvotes: 0

Views: 525

Answers (2)

asprin
asprin

Reputation: 9823

Try this

session_start();
if(!$_POST['description']){
echo "<script>alert(\"Please fill out all fields\");";
echo "window.location.href='post_job.php';";
echo "</script>";
}

Although I must add the way you intend to show your message isn't in a good manner. Validating through Ajax or javascript before the form is submitted is a good route to follow. Keep this way as a backup plan in case javascript is disabled on the client's system.

Upvotes: 1

Kenzo
Kenzo

Reputation: 3633

The echo with the tag in it sends output to the browser. Use your preferred JavaScript way of redirecting within the script tag instead.

Upvotes: 0

Related Questions