0

I am trying to do a live search from database using jquery, ajax and php. After getting result I want to set value of input field with selected option from result. Code returns live search result but did not set value of selected option to input field.

<html>
<body>
  <input type="text" id="search" placeholder="Search" />
  <div class="display"></div>

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $("#search").keyup(function() {
        var searchid = $(this).val();
        $.ajax({
          type: "POST",
          url: "result.php",
          data: {
            search: searchid
          },
          success: function(data) {
            $(".display").html(data).show();
          }
        });
      });
    });
  </script>
  <script>
    $(document).ready(function() {
      $(".sel").click(function() {
        var value = $(this).text();
        $('#search').val(value);
      });
    });
  </script>
</body>
</html>
<?php
  $q = $_POST['search'];
  $con = mysqli_connect("localhost", "root", "", "testing");
  $query = "select name from test where name like '%$q%';";
  $result = mysqli_query($con, $query);

  while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
  {
    $name = $row['name'];
    echo '<div class="sel">'.$name.'</div>';
  }
?>
Star
  • 3,222
  • 5
  • 32
  • 48
rohit phogat
  • 137
  • 1
  • 10
  • You need to use a delegated event handler on the `.sel` elements, as they are appended to the DOM after it was loaded. You can also combine the logic in both your document.ready handlers in to a single one. – Rory McCrossan Nov 06 '17 at 16:18
  • ***Also note that your PHP code is wide open to injection attacks***. I'd suggest you change the logic to use prepared statements ASAP, before your site is compromised. – Rory McCrossan Nov 06 '17 at 16:20
  • Thank you very much. I am just testing it on localhost. I will use better code for security. – rohit phogat Nov 06 '17 at 16:27

0 Answers0