Reputation: 2198
I'm using jQuery autocomplete and trying to get it to go directly to the link when I click on suggestion or press enter. Here's the code I used:
<script>
$(function() {
$( "#search" ).autocomplete({
source: 'search.php',
select: function(event, ui) {
$(this).val(ui.item.value);
$(this).parents("form").submit(); // this will submit the form.
}
});
});
</script>
Then I have my php code for search: '
if ($_POST['search'] != null) {
//die("asdf: " . $_POST['search']);
$search = $_POST['search'];
$result = mysqli_query($con,"SELECT * FROM question WHERE text LIKE '%$search%'");
while($row = mysqli_fetch_array($result)) {
$text = $row['text'];
$question_id = $row['question_id'];
//die($search . " " . $text);
if ($search == $text){
header("Location: http://localhost/showstats.php?question_id=$question_id");
die();
}
echo "<br>";
echo " <a href=\"showstats.php?question_id=" . $question_id;
echo "\">$text</a> ";
//echo "<br>";
}}
The problem is when I click on suggestion it doesn't redirect to "showstats.php?question_id=$question_id"
, insted give me a blank result page.
And when I insert die($search . " " . $text);
inside if statement it's showing me text 2 times, so I know it enters the body of it statement.
Upvotes: 0
Views: 89
Reputation: 766
When you select a suggestion, the event occurs in the client so this code in your PHP is not really necessary:
if ($search == $text) {
header("Location: http://localhost/showstats.php?question_id=$question_id");
die();
}
Instead, when you select a suggestion, try triggering the redirection from jQuery:
<script>
$(function() {
$( "#search" ).autocomplete({
source: 'search.php',
select: function(event, ui) {
// This will redirect you to whatever URL is in ui.item.value:
window.location = ui.item.value;
}
});
});
</script>
Upvotes: 0
Reputation: 11
also worth escaping your sql...
$search = $_POST['search'];
$search = mysqli_real_escape_string($search);
$result = mysqli_query($con, "SELECT * FROM question WHERE text LIKE '%$search%'") or die(mysqli_error($con));
Upvotes: 1
Reputation: 694
It is because your headers are already sent, you have started your output, hence the redirect will not work.
Try buffering your output.
Upvotes: 0