2015-08-23 184 views
0

我有一個搜索框,使用PHP搜索電影數據庫(查詢數據庫的電影標題,並從輸入框中獲取信息使用$ _POST)和jQuery(以立即搜索)。我希望它能夠在輸入框沒有任何內容的情況下顯示電影片名(目前顯示)。PHP的jQuery檢查輸入框是否爲空

這裏是形式:

<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> 

這裏是jQuery的:

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

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

這裏是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); 

?> 

我曾試圖彌補沒有電影標題出現在輸入框中時什麼也沒有:

無論如何解決這個越來越呢?

謝謝。

回答

3

你應該修剪值,並檢查它是否是一個空字符串觸發Ajax請求之前:

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); 
    }) 
} 

而且情況下也加入了PHP腳本檢查和形式沒有js函數提交:

+0

謝謝 - 但是,而不是顯示沒有電影,這種修改顯示最近的搜索電影? – Hp123

+0

確實,讓我編輯我的答案,如果字符串爲空,則應該用消息替換最新的搜索結果。 – taxicala

+1

謝謝!作品很棒:) – Hp123