Как автозаполнить загрузчик PHP MySQL AJAX из базы данных - PullRequest
1 голос
/ 05 мая 2019

автозаполнение не работает. Я хочу получить данные из базы данных mysql, например, опция google. Мой файл не работает, ничего не отображается, когда мы нажимаем кнопку выбора данных из опции sugested

пожалуйста, предложите хороший код мой код не работает сейчас не работает, сэр и автоматический выбор не показывает аналогичный ответ эта ссылка показывает, но не выбирает какие-либо данные при выборе ключа это ссылка, где ничего не показано

     <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    <!--my file not working auto complete address from database-->
    <!--code inclide file of botstarp -->
<script        
   src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <!--code of auto fetch-->
      <script>
     $(document).ready(function () {
       $('#Country').typeahead({
        source: function (query, result) {
            $.ajax({
                url:"autoselect_jquery5.php",
                data:'query=' + query,            
                dataType:"json",
                type:"POST",
                success: function (data) {
                    result($.map(data, function (item) {
                        return item;
                    }));
                }
            });
           }
        });
     });
      </script>
       </head>


       <body>
       div class="container" style="width:600px;">
      <h2 align="center">Autocomplete Textbox using Bootstrap Typeahead with Ajax PHP</h2>

                 <label>Search Country</label>
       <input type="text"name="country"id="country"autocomplete="off"placeholder="Country" />
     </div>
 </body>
   <   /html> 

       <!--second file which fetching data from from database -->
     // autoselect_jquery5.php file for fetch code
       <?php
     include 'database.php';

     if (isset($_POST['query'])) {
     $search_query = $_POST['query'];


      $query = "SELECT * FROM transporter WHERE address LIKE 
  '%".$search_query."%' LIMIT 12";
   $result = mysqli_query($link, $query);
  $data = array();

    if(mysqli_num_rows($result) > 0)
   {
    while($row = mysqli_fetch_assoc($result))
     {
        $data[] = $row["address"];
     }
      echo json_encode($data);
          }
      }
       ?>




    }

Ответы [ 2 ]

0 голосов
/ 05 мая 2019

У вас есть некоторые ошибки, я объясняю вам в комментариях в вашем коде.

Я надеюсь, что смогу вам помочь. Я скопировал ваш код и исправил его.

Сейчас работает. Попробуйте и прокомментируйте меня.

Шаги:

1) Импортировать файл базы данных (на локальный сервер).

База данных ссылок: https://drive.google.com/drive/u/1/folders/1JhXXPQ4QHsHssTbpdnhL_cBOrnK7Q3nB

2) Скопируйте в папку локального сервера файл autocomplete.html.

   <!DOCTYPE html>
    <html>
    <head>
    <title></title>
    <!--my file not working auto complete address from database-->
    <!--code inclide file of botstarp -->
<script        
   src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>  
   <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
        <!--code of auto fetch-->
      <script>
     $(document).ready(function () {
       $('#country').typeahead({ // Your #Country ID is different that you using in input 
        // #Country <> 
        source: function (query, result) {
            $.ajax({
                url:"database.php",
                data:'query=' + query,            
                dataType:"json",
                type:"POST",
                success: function (data) {
                    result($.map(data, function (item) {
                        return item;
                    }));
                }
            });
           }
        });
     });
      </script>
       </head>


       <body>
       <div class="container" style="width:600px;">
      <h2 align="center">Autocomplete Textbox using Bootstrap Typeahead with Ajax PHP</h2>

                 <label>Search Country</label>
       <input type="text"name="country"id="country"autocomplete="off"placeholder="Country" />
     </div>
 </body>
</html> 

3) Скопируйте в ту же папку код php.

<?php		
	
	$host = 'localhost'; //This is your host, if you working locally your host will be localhost
	$user = 'root'; //The name of the your user in localhost server
	$pass = 'root'; //The password of the your user in localhost server
	$db_name = 'countries'; //The name of the database that you using

	$keyword = strval($_POST['query']); // 
	$search_param = "{$keyword}%";
	$conn =new mysqli($host, $user, $pass, $db_name);

	$sql = $conn->prepare("SELECT * FROM country WHERE name LIKE ?");
	$sql->bind_param("s",$search_param);			
	$sql->execute();
	$result = $sql->get_result();
	if ($result->num_rows > 0) {
		while($row = $result->fetch_assoc()) {
		$countryResult[] = $row["name"];
		}
		echo json_encode($countryResult);
	}
	$conn->close();
?>

4) Все кончено.

0 голосов
/ 05 мая 2019

для автозаполнения, вы можете использовать typehead.js, он работает с проверкой начальной загрузки ниже, например.

Как мы устанавливаем remote в Typeahead.js?

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...