M Johnson
M Johnson

Reputation: 15

PHP by keypress jquery

I want to make search in my username database but it doesnt recognize keypress function. also, I want to prevent search.php on first load (can't use isset because there is no button) this is my index.php

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<head>
  <title></title>
  <?php  include 'search.php'; ?>

  <script>
    $(document).ready(function() {
      $("#textbox1").keypress(function() {
        $.ajax({
          type: "GET",
          url: "search.php",
          success: function(data) {
            $("#main").html(data);
          }
        });
      });
    });
  </script>

  <form method="POST">
    enter keyword to search<br>
    <input type="text" name="textbox1" id="textbox1">
    <br><br>
    <div id="main"></div>
  </form>
</head>

<body>

This is my search.php. the connection.php is working proper. so I'm not pasting it here

<?php

    include 'connection.php';

    $search_value = $_POST['textbox1'];
    $query = "SELECT username FROM users WHERE username LIKE '" . $search_value . "%'";
    $conn_status = mysqli_query($conn, $query);

    while($row = $conn_status->fetch_assoc())
    {
        echo $row['username'] . '<br>';
    }
?>

Upvotes: 0

Views: 627

Answers (2)

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

You should send the field value to your PHP page as data in your ajax request like :

$.ajax({
    type: "GET",
    url: "search.php",
    data: {textbox1: $(this).val()},
    success: function (data) {
          $("#main").html(data);
    }
});

NOTE : I suggest the use of input event in this case since it's more efficient when tracking the user input :

$("#textbox1").on('input', function(){
    //Your logic here
});

Upvotes: 2

Yolo
Yolo

Reputation: 1579

This snippet is a working one with amendments since you have wrong HTML as well as forgetting to send data to the server.

<!DOCTYPE html>
<html>

<head>
  <title></title>
</head>

<body>
  <form method="POST">
    enter keyword to search<br>
    <input type="text" name="textbox1" id="textbox1">
    <br><br>
    <div id="main"></div>
  </form>


  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script>
    $(document).ready(function() {

      $("#textbox1").on('input',function() {

        var searchText = $(this).val();
        console.log("Calling PHP with value:" + searchText);

        $.ajax({
          type: "GET",
          data: "textbox1=" + searchText,
          url: "search.php",
          success: function(data) {
            $("#main").html(data);
          },
          error: function (xhr, ajaxOptions, thrownError) {
            console.log(xhr.responseText);
          }
        });
      });
    });
  </script>
</body>

</html>

Upvotes: 0

Related Questions