Link to home
Start Free TrialLog in
Avatar of Crazy Horse
Crazy HorseFlag for South Africa

asked on

stop form action from going to page if search field is empty

I have a search field in a form that looks like this on my index.php page.

 
 <form action="search.php" method="post">

Open in new window


The search function is working fine but I don't want the page to actually go to search.php if the search field is empty i.e.: they just click "search" without actually inputting anything.

I tried this above the form:

 $error = "";
		  
		  if($_SERVER['REQUEST_METHOD'] == "POST"){
			  
			  if (empty($_POST['search'])){
				  
				  $error .="Please enter a search term";
				  
			  } 
		  }

Open in new window


But it still posts the search.php page and shows the error there. Is it possible to stop the page from redirecting to search.php if the search input is empty?
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Yes, it's possible, but this is not a PHP question.  You use JavaScript to influence behaviors in the client browser.  You might try using the "required" attribute in the search field.
http://www.w3schools.com/tags/att_input_required.asp
Also, you might rethink the use of a POST request for a search.  If you use GET instead of POST, your clients can bookmark the page, they can share the link with others, etc.  The search parameters are in the URL.  It's just a much more user-friendly way to work the issue.
Avatar of Crazy Horse

ASKER

Thanks Ray. But "required" doesn't work with safari, I need something that does.
Avatar of Dave Baldwin
I use POST for my search functions and filter the values like crazy.  A 'Search' form is a Big target for spammers.  Too often the 'users' aren't 'user friendly'.
You have to do it twice in any case.  Use Javascript in the browser and PHP on the server.  Remember that spammers will bypass your form and send directly to your 'action' page.
ASKER CERTIFIED SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Works like a charm!