简体   繁体   English

在模式、警报或仅具有关闭 x 的弹出框中显示来自 html 搜索框的 mysql 查询结果

[英]Display mysql query result from a html search box in a modal, alert, or just a popup box that has closing x

I have been working IT for 16 years and I am new to coding.我已经在 IT 工作了 16 年,而且我是编码新手。 I am wanting to display a search result from a input html box and have it display data from mysql database into something like a modal, alert, or a popup box that has a closing x.我想显示来自输入 html 框的搜索结果,并让它将来自 mysql 数据库的数据显示为模态框、警报或具有关闭 x 的弹出框。 My database is nothing more than a word and definition.我的数据库只不过是一个词和定义。 The user will type a word they want a definition for and it will display in some sort of small box that will go away when clicked.用户将键入一个他们想要定义的单词,它会显示在某种小框中,单击时会 go 消失。 I found some code online that when entered and then click the submit button it just shows up below the input form and stays there.我在网上找到了一些代码,当输入然后单击提交按钮时,它只显示在输入表单下方并停留在那里。 Any help would be great.任何帮助都会很棒。 I feel like this should be simple but I have not been able to find anything that fits my description.我觉得这应该很简单,但我找不到任何符合我描述的东西。 Most of my findings show clicking a button and displaying the results.我的大部分发现都显示单击按钮并显示结果。 If this is something simple wonderful, but if I need to upload my code I found I can.如果这很简单,但如果我需要上传我的代码,我发现我可以。 I apologize now if I am not asking properly.如果我没有正确询问,我现在道歉。

<!DOCTYPE html>
<html>
   <head>
      <title>
         AJAX Search Example
      </title>
      <script>
         function fetch() {
           // GET SEARCH TERM
           var data = new FormData();
           data.append('search', document.getElementById("search").value);
           data.append('ajax', 1);
         
           // AJAX SEARCH REQUEST
           var xhr = new XMLHttpRequest();
           xhr.open('POST', "search.php", true);
           xhr.onload = function () {
             if (this.status==200) {
               var results = JSON.parse(this.response),
                   wrapper = document.getElementById("results");
               wrapper.innerHTML = "";
               if (results.length > 0) {
                 for(var res of results) {
                   var line = document.createElement("div");
                   line.innerHTML = res['name'] + " - " + res['definition'];
                   wrapper.appendChild(line);
                 }
               } else {
                 wrapper.innerHTML = "No results found";
               }
             } else {
               alert("ERROR LOADING FILE!");
             }
           };
           xhr.send(data);
           return false;
         }
      </script>
   </head>
   <body>
      <!-- [SEARCH FORM] -->
      <form onsubmit="return fetch();">
         <h1>SEARCH FOR USERS</h1>
         <input type="text" id="search" required/>
         <input type="submit" value="Search"/>
      </form>
      <!-- [SEARCH RESULTS] -->
      <div id="results"></div>
   </body>
</html>

search.php搜索.php

<?php
// (1) DATABASE CONFIG
// ! CHANGE THESE TO YOUR OWN !
define('DB_HOST', 'localhost');
define('DB_NAME', '');
define('DB_CHARSET', 'utf8');
define('DB_USER', 'root');
define('DB_PASSWORD', '');

// (2) CONNECT TO DATABASE
try {
  $pdo = new PDO(
    "mysql:host=" . DB_HOST . ";charset=" . DB_CHARSET . ";dbname=" . DB_NAME,
    DB_USER, DB_PASSWORD, [ PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false ]
  );
} catch (Exception $ex) {
  die($ex->getMessage());
}

// (3) SEARCH
$stmt = $pdo->prepare("SELECT * FROM `ot` WHERE `name` LIKE ? OR `name` LIKE ?");
$stmt->execute(["%" . $_POST['search'] . "%", "%" . $_POST['search'] . "%"]);
$results = $stmt->fetchAll();
if (isset($_POST['ajax'])) { echo json_encode($results); }

Seeing as you are successfully appending the child node to the document it sounds to me as though the code you're using looks a little like this...看到您成功地将子节点附加到文档中,在我看来,您使用的代码看起来有点像这样......

var popup       = document.createElement("div");           // Create the popup container
popup.innerHTML = "<h1>Content</h1><p>Goes here....</p>";  // Add text/html inside of the container
document.body.appendChild(popup);                          // Add popup to the page

Your problem你的问题

Styling造型

Pop up messages aren't created just by adding an element to the page .弹出消息不是通过向页面添加元素来创建的。 What makes it a pop up is the styling that you add to it with CSS .使它弹出的原因是您使用CSS添加到其中的样式。

Removing移除

To remove an element from the page you have to attach an event listener which pick up on the created element being clicked and then calling the remove method.要从页面中删除元素,您必须附加一个事件侦听器,该事件侦听器拾取正在单击的已创建元素,然后调用remove方法。

Example Code示例代码

JS JS

// Create the element and the content
var popup       = document.createElement("div");
popup.innerHTML = "<h1>Content</h1><p>Goes here....</p>";

// Add a class for styling
popup.classList.add("popup");

// Add an onclick event listener
popup.onclick   = function(){this.remove();};

// Append the element to the document
document.body.appendChild(popup);

CSS CSS

This sample CSS simply places the popup in the central area on the screen.此示例CSS只是将弹出窗口放置在屏幕的中央区域。

Note that position: fixed;注意position: fixed; is the line which takes the element out of the traditional linear page structure.是将元素从传统的线性页面结构中取出的行。

.popup{
    position: fixed;
    top: 25%;
    left: 25%;
    width: 50%;
    min-height: 50px;
    background: #fff;
    border: 2px solid #000;
    border-radius: 20px;
    box-shadow: 0 0 20px 15px #000;
    padding: 5px 20px;
}

Working solution工作解决方案

Copy/paste this into your HTML file and it should work for you.将其复制/粘贴到您的 HTML 文件中,它应该适合您。 I've added plenty of comments to hopefully explain what is going on at each stage.我添加了大量评论,希望能解释每个阶段发生的事情。

<!DOCTYPE html>
<html>
<head>
    <title>
        AJAX Search Example
    </title>
    <script>
        function fetch() {
            // Get search term from form
            var data = new FormData();
            data.append('search', document.getElementById("search").value);
            data.append('ajax', 1);

            // Search
            var xhr = new XMLHttpRequest();    // Create the HTTP Request object
            xhr.open('POST', "search.php");    // Set connection parameters
            xhr.responseType = "json";         // Set response to JSON so that it auto parses

            // Event listener which checks status of the request and passes the response to
            // our pop up creating function
            xhr.onload = function(){        
                if(this.status == 200){
                    make_popup(this.response);
                }
            };
            xhr.send(data); // Send request
            return false;
        }

        function make_popup(response){

            // Create element and add class "popup"
            var popup = document.createElement("div");
            popup.classList.add("popup");

            // Create "close" for poup
            var close_popup = document.createElement("div");
            close_popup.innerHTML = "X";
            close_popup.classList.add("close_popup");

            // Set listener to remove the popup on click
            close_popup.onclick = function(){
                this.parentNode.remove();
            };

            // Add close to popup
            popup.appendChild(close_popup);

            /**
             * For each returned result we're going to create a new "p" element
             * which will contain the `name`, followed by a line break, and then
             * `definition` from the HTTP response the name will be in bold text.
             *
             * Markup will look like:
             *     <p> <b>NAME</b><br> DEFINTIION </p>
             * 
             */
            for(row in response){
                // Create the document elements we need
                let result  = document.createElement("p");
                let title   = document.createElement("b");
                let newline = document.createElement("br");

                // Create the text nodes for `name` and `definition`
                let title_text      = document.createTextNode(response[row].name);
                let definition_text = document.createTextNode(response[row].definition);

                // Add the elements together in the right order
                title.appendChild(title_text);
                result.appendChild(title);
                result.appendChild(newline);
                result.appendChild(definition_text);

                // Append the result to the popup
                popup.appendChild(result);
            }
            document.body.appendChild(popup);
        }

    </script>
    <style>
        .popup{
            position: fixed;
            top: 25%;
            left: 25%;
            width: 50%;
            min-height: 50px;
            background: #fff;
            border: 2px solid #000;
            border-radius: 20px;
            box-shadow: 0 0 20px 15px #000;
            padding: 5px 20px;
        }
        .close_popup{
            float: right;
            cursor: pointer;
            font-weight: bold;
            font-family: tahoma;
            border-radius: 50%;
            font-size: 15px;
            width: 25px;
            height: 25px;
            line-height: 25px;
            text-align: center;
            color: #fff;
            background: #000;
            z-index: 1000;
        }
    </style>
</head>
<body>
    <form onsubmit="return fetch();">
        <h1>SEARCH FOR USERS</h1>
        <input type="text" id="search" required/>
        <input type="submit" value="Search"/>
    </form>
</body>
</html>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM