Ajax搜索帖子错误

I need help with two things. First: if I hit empty submit button. It should show me a error. Second: If there is 0 results, it will give an error.

$(document).ready(function(){
    $(".search").click(function(){
        $.post("search.php", { keywords: $(".keywords").val() }, function(data){
            $("div#search").empty()
            $.each(data, function(){
                $("div#search").append("- <a href='#?id=" + this.id + "'>" + this.title + "</a><br>");
            });
        }, "json");
    });
});

--

$query = $db->prepare("SELECT `media`.`id`, `media`.`title` FROM `media` WHERE `media`.`title` LIKE :keywords");

$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';

if (empty($keywords) === true) {
    $error = 'error';
    echo json_encode( $error );
} else {
    $query->bindValue(':keywords', '%' . $keywords . '%', PDO::PARAM_STR);
    $arr = array();
    $query->execute();
    while( $row = $query->fetch(PDO::FETCH_ASSOC) ) {
        $arr[] = array( "id" => $row["id"], "title" => $row["title"]);
    }
    echo json_encode( $arr );
}

try using $(this) instead of this

OK I have painstakingly recreated (jsfiddle does not let you copy/paste) this on my local machine. Your html/js code should look like this:

<html>
    <head>
        <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    </head>
    <body>
        <input type="text" name="search" class="keywords">
        <input type="submit" name="submit" class="search">
        <div id="search"></div>
        <script>
            $(document).ready(function(){
                $(".search").click(function(){
                    $.post(
                        "search.php", 
                        { keywords: $(".keywords").val() }, 
                        function(data){
                              $("div#search").empty()
                          $("div#search").append(data);
                        }, 
                        "json"
                    );
                });
            });
        </script>
    </body>
</html>

And for the PHP search.php page:

<?php
$keywords = (isset($_POST['keywords']) === true) ? $_POST['keywords'] : '';
if (empty($keywords) === true) {
    echo json_encode( "error" );
}
else {
    // run mysql commands
    // if resultset == empty
    // echo json_encode( "error" );
    echo json_encode( "actual data" );
}
?>

To parse json data in javascript do this:

$.post(
  "search.php", 
  { keywords: $(".keywords").val() }, 
  function(data) {
    $("div#search").empty();
    obj = JSON.parse(data);
    $("div#search").append(obj.id + " " + obj.title);
  }, 
  "json"
 );