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 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']; ?>")' >
<?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 style="margin-top: 5.5em;">
<button type="button" data-bs-toggle="dropdown" aria-expanded="false">Search By</button>
<ul >
<li><a href="/isbn/title/?sch=<?php echo $_GET['sch']; ?>">Book Title</a></li>
<li><a href="/isbn/author/?sch=<?php echo $_GET['sch']; ?>">Author</a></li>
<li><a href="/isbn/teacher/?sch=<?php echo $_GET['sch']; ?>">Teacher</a></li>
</ul>
<input placeholder="<?php echo $placeholder; ?>" aria-label="Text input with dropdown button"
onblur="this.focus()" onfocus="this.value=''" type="text" id="search" autocomplete="off" <?php echo $disabled; ?> />
<input 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
CodePudding user response:
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'];