【问题标题】:Display “No matches found” or hide DIV results (AJAX & MySQL)显示“未找到匹配项”或隐藏 DIV 结果(AJAX 和 MySQL)
【发布时间】:2019-03-18 18:30:51
【问题描述】:

我有一个搜索栏,可用于显示 MySQL、PHP 和 JS 的 AJAX 实时搜索结果。

问题是当查询与 MySQL 数据库中的任何“名称”都不匹配时,我无法弄清楚如何让搜索结果显示“未找到匹配项”或完全隐藏结果 div

目前,当用户在搜索栏中键入与数据库中的任何“名称”都不匹配的内容时,AJAX 实时搜索结果下方会弹出一个空白结果。相反,我希望消息“未找到匹配项”来接管该空白结果。

我已经尝试了许多 else / if / echo 代码和不同顺序的组合,但到目前为止没有任何效果。我也在尝试一种不同的方法来显示/隐藏根据结果显示“未找到匹配项”的 div。

如何一劳永逸地修复此代码,以便当用户搜索与 MySQL 数据库中的任何名称不匹配的任何名称时,它会显示“未找到匹配项”?

以下是我目前正在使用的文件和代码:

index.php

<form>  
 <input type="text" id="search" class="search" data-js="form-text" 
  placeholder="Search Over 100+ Resources..." autocomplete="off">
 <button type="submit" class="Button" value="Submit"><i class="fa fa- 
  search"></i></button>
 <div id="display"></div>
<div id="no-results" style="display:none"><ul><li id='hover'>No matches 
 found</li></ul></div>
</form>

ajax.php

<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_GET['search'])) {
//Search box value assigning to $Name variable.
$Name = $_GET['search'];
//Search query.
$Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
 echo '<ul>';
 //Fetching result from database.
 while ($Result = MySQLi_fetch_array($ExecQuery)) {
   ?>
 <!-- Creating unordered list items.
    Calling javascript function named as "fill" found in "script.js" file.
    By passing fetched result as parameter. -->
 <li onclick='fill("<?php echo $Result['Name']; ?>")'>
 <a>
 <!-- Assigning searched result in "Search box" in "index.php" file. -->
   <?php 
 if ($ExecQuery > "0") {
 echo $Result['Name'];
 }
 else {
  echo "<li id='hover'>No matches found</li>";
 }
?>
</li></a>
<!-- Below php code is just for closing parenthesis. Don't be confused. -->
<?php
}}

?>
</ul>

script.js

//Getting value from "ajax.php".
function fill(Value) {
//Assigning value to "search" div in "index.php" file.
$('#search').val(Value);
//Hiding "display" div in "index.php" file.
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "index.php" file. This function will 
be called.
$('#no-results').hide();
$("#search").keyup(function() {
   //Assigning search box value to javascript variable named as "name".
   $('#display').hide();
   $('#no-results').css("display", "none");
   var name = $('#search').val();
   //Validating, if "name" is empty.
   if (name == "") {
       //Assigning empty value to "display" div in "index.php" file.
       $('#no-results').css("display", "none");
   }
   //If name is not empty.
   else {
       //AJAX is called.
       $.ajax({
           //AJAX type is "Post".
           type: "GET",
           //Data will be sent to "ajax.php".
           url: "ajax.php",
           //Data, that will be sent to "ajax.php".
           data: {
               //Assigning value of "name" into "search" variable.
               search: name
           },
           //If result found, this funtion will be called.
           success: function(html) {
               //Assigning result to "display" div in "index.php" file.
               $("#display").html(html).show();
           }
       });
   }
 });
 });

【问题讨论】:

    标签: javascript php mysql ajax


    【解决方案1】:

    更新

    您应该检查您的数据是否有效,您是否有任何来自数据库查询的结果,如果没有记录,那么您可以打印未找到数据消息。 您应该检查$ExecQuery 的输出并据此设置if 条件。 现在让我看看你的输出和结果,希望对你有所帮助。

    更新 ajax.php 最后更新的部分

    echo "<li onclick='fill(`".$Result['Name']."`)'>".$Result['Name']."</li>";
    

    完整的ajax.php

      <?php
        //Including Database configuration file.
        include "db.php";
        //Getting value of "search" variable from "script.js".
    if (isset($_GET['search'])) {
    //Search box value assigning to $Name variable.
    $Name = $_GET['search'];
    //Search query.
    $Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
    //Query execution
    $ExecQuery = MySQLi_query($con, $Query);
    //Creating unordered list to display result.
        if ($ExecQuery->num_rows > 0) {
             echo "<ul>";
             while ($Result = MySQLi_fetch_array($ExecQuery)) {
                // use the onclick function that defined in js file. you can use the `  sign in js instead of ' if you needed.
                echo "<li onclick='fill(`".$Result['Name']."`)'>".$Result['Name']."</li>";
             }
            echo "</ul>";
        }else{
            echo "<ul><li>No Result Found!</li></ul>";      
        }
    }
    die();
    ?>
    

    还有你的 ajax 代码。

    function fill(value) {
      console.log(value);
      $('#search').val(value);
      $('#display').hide();
    }
     $(document).ready(function() {
    //On pressing a key on "Search box" in "index.php" file. This function will be called.
    $("#search").keyup(function() {
       //Assigning search box value to javascript variable named as "name".
       $('#display').hide();
       $('#no-results').css("display", "none");
       var name = $('#search').val();
       //Validating, if "name" is empty.
       if (name == "") {
           //Assigning empty value to "display" div in "index.php" file.
           $('#no-results').css("display", "block");
       }
       //If name is not empty.
       else {
           //AJAX is called.
           $.ajax({
               //AJAX type is "Post".
               type: "GET",
               //Data will be sent to "ajax.php".
               url: "ajax.php",
               //Data, that will be sent to "ajax.php".
               data: {
                   //Assigning value of "name" into "search" variable.
                   search: name
               },
               //If result found, this funtion will be called.
               success: function(html) {
    
               if (html == '<ul><li>No Result Found!</li></ul>') {
                  $('#no-results').css("display", "block");
                }else{
                   //Assigning result to "display" div in "index.php" file.
                     $("#display").html(html).show();
                 }
    
               }
           });
       }
     });
     });
    

    根据需要更改其他部分。

    【讨论】:

    • @SCodeSK71 你有ajax代码吗?请检查您的问题并使用所有相关部分(HTML、PHP、Ajax 和您拥有的任何相关代码块)更新它
    • 如何让事情变得更容易。如果 MySql 中没有“名称”匹配,有没有办法什么都不显示?例如,如果用户键入“dhjfahdjhsjk”,搜索栏下不会弹出任何框。如果数据库中没有匹配的名称,我可以完全不触发 ajax 实时搜索。
    • @SCodeSK71 我根据您的反馈重写了答案,请再次检查并告诉我它对您有帮助。
    • 您为什么要从我的原始代码中删除代码//Getting value from "ajax.php". function fill(Value) { //Assigning value to "search" div in "index.php" file. $('#search').val(Value); //Hiding "display" div in "index.php" file. $('#display').hide(); }?现在我的填充功能不起作用。我试图将它添加到您的代码中,但它不再起作用了。你能让我的JS 文件中的填充功能与你的代码一起使用吗?
    • 如果您可以在stackoverflow.com/questions/55286480/…stackoverflow.com/questions/55286480/… 处帮助解决,我将新问题作为新问题发布了
    【解决方案2】:

    AJAX 是异步 Javascript 和 XML。为什么要发回 HTML?

    指针

    • 如果您通过 Ajax 执行此操作,我强烈建议您发送纯 HTML。您应该发回一些 JSON 数据并在客户端进行相应的处理。

    • 使用 PDO 代替 MySQLi

    解决方案 PHP

    <?php
    include "db.php";
    if (isset($_POST['search'])) {
      $Name = $_POST['search'];
      $Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
      $ExecQuery = MySQLi_query($con, $Query);
    
      $res = [];
      while ($Result = MySQLi_fetch_array($ExecQuery)) {
        $res[] = $Result['Name'];
      }
    
      echo json_encode($res);
    }
    

    解决方案 Javascript:

    $.ajax({
      //AJAX type is "Post".
      type: "POST",
      //Data will be sent to "ajax.php".
      url: "ajax.php",
      //Data, that will be sent to "ajax.php".
      data: {
        //Assigning value of "name" into "search" variable.
        search: name
      },
      //If result found, this funtion will be called.
      success: function(data) {
        //Assigning result to "display" div in "search.php" file.
        const list = JSON.parse(data);
        const html = list.length > 0 ? 
          list.map(name=>{
            `<li onclick="${name}">
               <a>${name}</a>
            </li>`
          }).join("") :
          `<li>No matches found</li>`
    
        $("#display").html(`<ul>${html}</ul>`).show();
      }
    });
    

    【讨论】:

    • @SCodeSK71 嘿,对不起,我想我们住在不同的时区。我在等你的评论。下班我去看看。
    • 感谢您的帮助,我将阅读 JSON 和 PDO。我现在可以使用它,但是弹出了一个新问题,即 onclick 填充功能不起作用。如果您可以帮助回答,我已将其作为一个新问题发布在这里? stackoverflow.com/questions/55286480/…
    猜你喜欢
    • 2011-10-04
    • 2012-09-15
    • 2014-05-22
    • 2020-09-05
    • 2022-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多