rharper
rharper

Reputation: 565

PHP jQuery check if input box is empty

I've got a search box that uses PHP to search a film database(to query the database for film titles and get the information from the input box using $_POST) and jQuery (to make it an instant search). I want it so that when the input box has nothing in it, no film titles show up (It currently shows up).

Here is the form:

<form action="" method="post">

    <input type="text" autocomplete="off" name="search" placeholder="Search for movies or genres..." onkeyup="searchq();" />
    <input type="submit" value=">>" />
    <div id="outp">

    </div>

</form>

Here is the jQuery:

function searchq(){
    var searchTxt = $("input[name='search']").val();

    $.post("search.php", {searchVal: searchTxt}, function(out) {
        $("#outp").html(out);
    })
}

And here is search.php:

<?php
include('db_con.php');

$out = '';

if (isset($_POST['searchVal'])){
    $searchq = $_POST['searchVal'];
    $searchq = preg_replace("#[^0-9a-z\-]#i", "", $searchq); 

    $q = mysqli_query($con, "SELECT id, title FROM films WHERE title LIKE '%$searchq%'") or die("Could not search!");
    $c = mysqli_num_rows($q); 

    if ($c == 0){
        $out = '<p>There was no search results!</p>';
    } else {
        while($line = mysqli_fetch_array($q)){
            $filmt = $line['title'];
            $id = $line['id'];

            $out .= '<div> <a href="list.php?id=' . $id . '">'.$filmt. '</a></div>';
        }
    }
}

echo($out);

?>

What I have tried to make no movie titles appear when nothing is in the input box:

Anyway of getting around this?

Thanks.

Upvotes: 0

Views: 252

Answers (1)

taxicala
taxicala

Reputation: 21759

You should trim the value and check if it's an empty string before triggering the ajax request:

function searchq(){
    var searchTxt = $("input[name='search']").val();
    if (searchTxt.trim() === "") {
         $("#outp").html("<p>Please enter a query in the search input.</p>");  //Or any other message :)
         return;
    }
    $.post("search.php", {searchVal: searchTxt}, function(out) {
        $("#outp").html(out);
    })
}

And also add a check in the PHP script as well in case the form is submitted without the js function:

<?php
include('db_con.php');

$out = '';
$seachVal = isset($_POST['searchVal']) ? $_POST['searchVal'] : false;

if ($seachVal){
    $searchq = $_POST['searchVal'];
    $searchq = preg_replace("#[^0-9a-z\-]#i", "", $searchq); 

    $q = mysqli_query($con, "SELECT id, title FROM films WHERE title LIKE '%$searchq%'") or die("Could not search!");
    $c = mysqli_num_rows($q); 

    if ($c == 0){
        $out = '<p>There was no search results!</p>';
    } else {
        while($line = mysqli_fetch_array($q)){
            $filmt = $line['title'];
            $id = $line['id'];

            $out .= '<div> <a href="list.php?id=' . $id . '">'.$filmt. '</a></div>';
        }
    }
}

echo($out);

?>

Upvotes: 3

Related Questions