0

I've tried so many methods from stackoverflow and other websites but whenever i succeed in hiding the div. No search result is displayed at all.

I've tried the :empty selector and fiddling around with the php code and js code. but since i'm very new to this i just can't seem to crack the error. What am i doing wrong?

My HTML

            <div class='search'>
            <form class="searchbox" action='index.php' method='post' autocomplete='off'>
                <input type='text' name='search' class='searchform' placeholder='Søg efter skole...' onkeyup="searchq();">
            </form>
            <div id="output"></div>
        </div>

PHP

    <?php

include("connection.php");
$output = '';
//collect

if(isset($_POST['searchVal'])) {
    $searchq = $_POST['searchVal'];
    $searchq = preg_replace("#[^a-zA-Z0-9æøå]#i"," ", $searchq);

    $query = mysqli_query($mysqli, "SELECT * FROM `products` WHERE name LIKE '%$searchq%'") or die("could not search");
    $count = mysqli_num_rows($query);

     if($_POST['searchVal'] == NULL) {
        $output = '';
    } else {

        while($row = mysqli_fetch_array($query)) {            
            $name = $row['name'];
            $id = $row['id'];
            $output .= '<a href="kantine.php?id='.$id.'" class="searchres">'.$name.'</a><br>';
        }  
    }
}

echo "<div class='output'>$output</div>";

?>

And JS

                function searchq() {
                var searchTxt = $("input[name='search']").val();
                $.post("search.php", {
                    searchVal: searchTxt
                }, function(output) {
                    $("#output").html(output);
                });
            }

Shaydx
  • 97
  • 1
  • 8
  • 2
    Your script is at risk of [SQL Injection Attack](https://stackoverflow.com/q/60174/5914775). Have a look at what happened to [Little Bobby Tables](http://bobby-tables.com/). Even [if you are escaping inputs, its not safe!](https://stackoverflow.com/q/5741187/5914775). Use [prepared parameterized statements](https://php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead. – Tom Udding Apr 03 '18 at 16:58
  • You can set the default style for #output to display:none, and then show it after filling it with the output in the post callback. – Don't Panic Apr 03 '18 at 17:00

1 Answers1

1

HTML

<div class='search'>
        <form class="searchbox" action='index.php' method='post' autocomplete='off'>
            <input type='text' name='search' class='searchform' placeholder='Søg efter skole...' onkeyup="searchq();">
        </form>
        <div id="output" style="display: none;"></div>
</div>

PHP

.....
echo $output;

JS

function searchq() {
    var searchTxt = $("input[name='search']").val();
    $.post("search.php", {
        searchVal: searchTxt
    }, function(output) {
        $("#output").html(output);
        if(output.length > 0) {
            $("#output").show();
        }
    });
}
Adam J
  • 506
  • 3
  • 17