0

I have a live search setup and working properly using on post value. I would like to add a parameter to my DB query that involves an additional "post" value. This is using php and ajax.

The variable $school shows up on in the text field and is populated by the $_GET['sch'] value. The query shows empty when the ajax is executed. (using echo $Query)

When "echoed", The &Query looks like this:
SELECT * FROM teachers WHERE FullName LIKE %test% and shcool_id = ''

Here is the PHP

<?php
if (isset($_POST['search'])) {
    $school = $_GET['sch'];
    $Name = $_POST['search'];
    $Query = "SELECT * FROM teachers WHERE fullName LIKE '%$Name%' AND school_id='$school' ";
    $ExecQuery = MySQLi_query($conn, $Query);
    echo '<div class="list-group" style="text-align:left;">';
    while($Result = MySQLi_fetch_array($ExecQuery)) {
?>
<a href="?id=<?php echo $Result['teacher_id']; ?>&sch=<?php echo $Result['school_id']; ?>" type="button" width="100%" onclick='fill("<?php echo $Result['fullName']; ?>")' class="list-group-item list-group-item-action">
<?php echo $Result['fullName']; ?>
</a>

<?php
    }
}
$conn->close();
?>
</div>

Here is the script file:

function fill(Value) {
   $('#search').val(Value);
   $('#display').hide();
}
$(document).ready(function() {
   $("#search").keyup(function() {
       var name = $('#search').val();
       if (name == "") {
           $("#display").html("");
       }
       else {
           $.ajax({
               type: "POST",
               url: "ajax.php",
               data: {
                   search: name
               },
               success: function(html) {
                   $("#display").html(html).show();
               }
           });
       }
   });
});

Here is the form:

<div class="input-group" style="margin-top: 5.5em;">
<button class="btn btn-outline-primary dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">Search By</button>
      <ul class="dropdown-menu">
        <li><a class="dropdown-item" href="/isbn/title/?sch=<?php echo $_GET['sch']; ?>">Book Title</a></li>
        <li><a class="dropdown-item" href="/isbn/author/?sch=<?php echo $_GET['sch']; ?>">Author</a></li>
        <li><a class="dropdown-item" href="/isbn/teacher/?sch=<?php echo $_GET['sch']; ?>">Teacher</a></li>
      </ul>
    <input placeholder="<?php echo $placeholder; ?>" class="form-control" aria-label="Text input with dropdown button"
    onblur="this.focus()" onfocus="this.value=''" type="text" id="search" autocomplete="off" <?php echo $disabled; ?> />
    <input class="form-control" type="text" id="school" value="<?php echo $_GET['sch']; ?>" />
    <br>
    <div id="display" style="width: 100%;"></div>
</div>

I tried to assign data. I've tried adding the var = school, etc I've tried adding the GET value directy on the PHP page I can see the value is populated in the id="school" text box.

data: {
    search: name, school: school
},

to the ajax file

Ant
  • 3
  • 3
  • 1
    **Warning:** Your code is vulnerable to SQL Injection attacks. You should use parameterised queries and prepared statements to help prevent attackers from compromising your database by using malicious input values. http://bobby-tables.com gives an explanation of the risks, as well as some examples of how to write your queries safely using PHP / mysqli. **Never** insert unsanitised data directly into your SQL. The way your code is written now, someone could easily steal, incorrectly change, or even delete your data. – ADyson Oct 31 '22 at 15:36
  • https://phpdelusions.net/mysqli also contains good examples of writing safe SQL using mysqli. See also the [mysqli documentation](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) and this: [How can I prevent SQL injection in PHP?](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) . Parameterising your queries will also greatly reduce the risk of accidental syntax errors as a result of un-escaped or incorrectly quoted input values. If you learnt your current technique from a tutorial or book, please don't use it again. – ADyson Oct 31 '22 at 15:36
  • The problem is the $_GET value exists on the initial page when you load it, but it isn't present in the AJAX request you send subsequently - each request to the server has completely separate parameters. So you need to take that value from the current page and pass it into the AJAX request - one way to do that is shown in the answer below. – ADyson Oct 31 '22 at 15:37

1 Answers1

1

Get your query params before ajax call.

let sch = '';
let queryParms = new URLSearchParams(window.location.search);

if (queryParms) {
  sch = queryParms.get('sch');
}
...
 
$.ajax({
  type: "POST",
  url: "ajax.php",
  data: {
    search: name,
    sch: queryParms.get('sch')
  },
  success: function(html) {
    $("#display").html(html).show();
  }
});

At the backend use and check for non empty value.

$_POST['sch'];
  • Thank you for getting back to me so quickly! I am sure this will work for me. I'm just not 100% sure where to add it to the existing script. I placed it where I thought it should go (based on my limited knowledge). It did keep the $_GET['] information as was my problem. I'll continue to work on it with this new information! Thank you again. – Ant Oct 31 '22 at 16:24