Reputation: 347
When a user does a search on my website, and there is only one entry, then I want to redirect the user to the search result. The current way that I am doing this is poor. Here is how I am currently doing this:
If there is only one search result on the search result page, then I render a hidden input with an ID of "redirect" and a value of the link to redirect to. In the javascript, if the hidden input with ID "redirect" exists, then the user is redirected to the value of the element.
It's a poor way to do this because the single search result is loaded first, so the user actually sees that there is one search result. Then, it loads after, say, 3 seconds.
Is there a better way to do this?
Upvotes: 1
Views: 232
Reputation: 13733
The issue with your logic is that you're waiting for something in the page to load THEN redirecting. I think a more elegant solution is to change the flow of things to give you a little more flexibility.
First, you're going to want to preprocess your query and check for the pertinent information; if there is one result, use the header();
redirects as mentioned. You may need to add some more information to the result set (database table) to make this possible.
I think taking this a step further, however, would be to redirect certain terms automatically as well. You'll kill two birds with one stone.
Let's say you have a database that is term
and url
- you could add certain terms to the list that also serve as a redirect. This is great for certain keywords that there are variations of. Use this sparingly though - it is great to use in conjunction with your site statistics. It may help you in instances where 0 records are shown.
Upvotes: 1
Reputation: 46620
<?php
//Query & other stuff
$num_of_results=mysql_num_rows($result);
if($num_of_results==0){
//no results
}elseif($num_of_results==1){
//only 1 result
//pseudo-code
//get id or controller ect from result set
header('Location: ./page/'.$id);
die();
}else{
//normal display of search results
while($row=.......){
}
}
?>
Upvotes: 1
Reputation: 15390
You should use PHP to determine if there is only one result, then do a server-side redirect like so:
header( 'Location: http://www.yoursite.com/redirect_page.html' );
exit;
Before printing anything to the page, check to see if there is only one result, and if so, render that script and exit so that nothing else gets processed.
Upvotes: 1
Reputation: 1686
You could use the header() PHP function to redirect if there is only 1 result.
header("Location: http://www.example.com/");
Upvotes: 3