I have a search bar with AJAX, MySQL, PHP, and JS. The search bar gives live search results in a div in a list and works in that respect.
My problem is the live search results in the div list when clicked on do not fill the search bar's input. Nothing happens and the list just stays open unless I click out of it. I used to have it working in my old code where when you click on any result it fills the search bar's input, but ever since I rewrote the whole code I can't figure out why the onclick and fill functions aren't working now.
How can I fix this code so that when a user clicks on one of the results in the live search result list it fills the search bar's input?
Here is what I've tried and currently have as my code in the following files:
index.php
<form>
<input type="text" id="search" class="search" data-js="form-text"
placeholder="Search Over 100+ Resources..." autocomplete="off">
<button type="submit" class="Button" value="Submit"><i class="fa fa-
search"></i></button>
<div id="display"></div>
<div id="backspace" style="display:none"></div>
</form>
script.js
//Getting value from "ajax.php".
function fill(Value) {
//Assigning value to "search" div in "index.php" file.
$('#search').val(Value);
//Hiding "display" div in "index.php" file.
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "indexd.php" file. This function will
be called.
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
$('#display').hide();
$('#backspace').css("display", "none");
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "index.php" file.
$('#backspace').css("display", "block");
}
//If name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "GET".
type: "GET",
//Data will be sent to "ajax.php".
url: "ajax.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this funtion will be called.
success: function(html) {
//Assigning result to "display" div in "index.php" file.
$("#display").html(html).show();
}
});
}
});
});
ajax.php
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_GET['search'])) {
//Search box value assigning to $Name variable.
$Name = $_GET['search'];
//Search query.
$Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
if ($ExecQuery->num_rows > 0) {
echo "<ul>";
while ($Result = MySQLi_fetch_array($ExecQuery)) {
echo "<li onclick='fill".$Result['Name']."'>".$Result['Name']."
</li>";
}
echo "</ul>";
}
}
die();
?>
you can use the ` sign instead of the single and double quotation for javascript.
Here you should just update the line 16 at ajax.php file like this.
echo "<li onclick='fill(`".$Result['Name']."`)'>".$Result['Name']."
Complete code
ajax.php file
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_GET['search'])) {
//Search box value assigning to $Name variable.
$Name = $_GET['search'];
//Search query.
$Query = "SELECT Name FROM search WHERE Name LIKE '$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display result.
if ($ExecQuery->num_rows > 0) {
echo "<ul>";
while ($Result = MySQLi_fetch_array($ExecQuery)) {
echo "<li onclick='fill(`".$Result['Name']."`)'>".$Result['Name']."
</li>";
}
echo "</ul>";
}
}
die();
?>
JS codes.
//Getting value from "ajax.php".
function fill(Value) {
//Assigning value to "search" div in "index.php" file.
$('#search').val(Value);
//Hiding "display" div in "index.php" file.
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "indexd.php" file. This function will be called.
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
$('#display').hide();
$('#backspace').css("display", "none");
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "index.php" file.
$('#backspace').css("display", "block");
}
//If name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "GET".
type: "GET",
//Data will be sent to "ajax.php".
url: "ajax.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this funtion will be called.
success: function(html) {
if (html == '<ul><li>No Result Found!</li></ul>') {
$('#no-results').css("display", "block");
}else{
//Assigning result to "display" div in "index.php" file.
$("#display").html(html).show();
}
}
});
}
});
});
Related
I'm trying to create a live search bar where I type names and I'm getting results from my database.
This is my project structure:
The files I'm using are map.js where I have my ajax call.
My two php files one for mysql connection and one to retrieve the data from the database.
And last my map.hbs where is my search bar.
map.js
function fill(Value) {
//Assigning value to "search" div in "map.hbs" file.
$('#search').val(Value);
//Hiding "display" div in "map.hbs file.
$('#display').hide();
}
$(document).ready(function() {
//On pressing a key on "Search box" in "map.hbs" file. This function will be called.
$("#search").keyup(function() {
//Assigning search box value to javascript variable named as "name".
var name = $('#search').val();
//Validating, if "name" is empty.
if (name == "") {
//Assigning empty value to "display" div in "map.hbs" file.
$("#display").html("");
}
//If the name is not empty.
else {
//AJAX is called.
$.ajax({
//AJAX type is "Post".
method: "POST",
//Data will be sent to "ajax.php".
url: "/php/loadData.php",
//Data, that will be sent to "ajax.php".
data: {
//Assigning value of "name" into "search" variable.
search: name
},
//If result found, this function will be called.
success: function(html) {
//Assigning result to "display" div in "map.hbs" file.
$("#display").html(html).show();
}
});
}
});
});
db.php
<?php
$con = MySQLi_connect(
"localhost", //Server host name.
"root", //Database username.
"", //Database password.
"covid_database" //Database name or anything you would like to call it.
);
//Check connection
if (MySQLi_connect_errno()) {
echo "Failed to connect to MySQL: " . MySQLi_connect_error();
}
?>
loadData.php
<?php
//Including Database configuration file.
include "db.php";
//Getting value of "search" variable from "script.js".
if (isset($_POST['search'])) {
//Search box value assigning to $Name variable.
$Name = $_POST['search'];
//Search query.
$Query = "SELECT name FROM pois WHERE name LIKE '%$Name%' LIMIT 5";
//Query execution
$ExecQuery = MySQLi_query($con, $Query);
//Creating unordered list to display the result.
echo '
<ul>
';
//Fetching result from the database.
// while ($Result = MySQLi_fetch_array($ExecQuery)) {
// ?>
// <!-- Creating unordered list items.
// Calling javascript function named as "fill" found in "map.js" file.
// By passing fetched result as a parameter. -->
// <li onclick='fill("<?php echo $Result['Name']; ?>")'>
// <a>
// <!-- Assigning searched result in "Search box" in "map.hbs" file. -->
// <?php echo $Result['Name']; ?>
// </li></a>
// <!-- Below php code is just for closing parenthesis. Don't be confused. -->
// <?php
// }}
// ?>
// </ul>
?>
map.hbs
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
{{!-- Search Bar --}}
<form class="form-inline my-2 my-lg-0">
<input class="form-control mr-sm-2" type="text" id="search" placeholder="Search" aria-label="Search">
<button class="btn btn-outline-success my-2 my-sm-0" type="submit" oninput="triggerSearch()">Search</button>
<div id="display">
</div>
</form>
<script src="/map.js"></script>
Your server, which you seem to have written in Node.js, does not recognise the URL you are requesting. This would be because you haven't written an endpoint handler for it.
Your options:
Write an endpoint handler in JS that runs the PHP (Node.js is not the ideal for this, but I believe it is possible).
Run a different server which has decent PHP support (such as Nginx or Apache HTTPD.
Rewrite the PHP program in JavaScript
I'd go for the latter myself, mixing server-side languages is usually more complication than it is worth.
I am trying to write a simple delete function for a comment system that i am working on. the comments are stored in a database where each comment has a cid that is incremented automatically. i have noticed that the user can only delete the first comment he/she has written but when a the user writes two comments and presses delete on the second one, the comment can not be deleted, can someone help fix this. here is my code. thank you for your help.
this is my meatballs.php file where i have the comments loaded.
<div class = "page" id = "comments">
<p class = "style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type = 'hidden' id = 'uid' value = '".$_SESSION['u_uid']."'>
<input type = 'hidden' id = 'date' value = '".date('Y-m-d H:i:s')."'>
<textarea id = 'message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'meatballsSubmit'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML=
$("#comments").load("getComments.php");
});
});
</script>
as for getCommetns.php file which retrieves the comments from the database.
<?php
include 'includes/dbh.inc.php';
session_start();
$sql = "SELECT * FROM meatballscomments";
$result = mysqli_query($conn, $sql);
while($row = $result->fetch_assoc()){
echo "<div class = 'comment-box'>";
echo '<span class = "user">'.$row['user_uid'].'</span><br><br>';
echo "<p>".htmlspecialchars($row['message'])."</p>";
echo '<span class = "datef">'.$row['date'].'</span>';
if(isset($_SESSION['u_id']) && $_SESSION['u_uid'] == $row['user_uid']){
echo "<br>";
echo "<input type = 'hidden' id = 'cid' value = '".$row['cid']."'>";
echo "<button class = 'btn' type = 'submit' id = 'meatballsDelete'>Delete</button>";
}
echo "</div><hr>";
}
?>
<script>
$(document).ready(function(){
$("#meatballsDelete").click(function(){
var cid = $("#cid").val();
$.ajax({
url: "deleteComment.php",
type: "POST",
async: false,
data: {
"cid": cid
}});
alert("Your comment has been deleted");
});
});
</script>
the deleteComment.php file that i have is very short and here it is.
<?php
include 'includes/dbh.inc.php';
$cid = $_POST['cid'];
$sql = "DELETE FROM meatballscomments WHERE cid = '$cid'";
$result = mysqli_query($conn, $sql);
You're assigning the same id on multiple html elements & using val() on the result of the jQuery selector which returns the first element with the id of cid. From jQuery:
Each id value must be used only once within a document. If more than
one element has been assigned the same ID, queries that use that ID
will only select the first matched element in the DOM.
Therefore there's no guarantee that it automatically grabs the right element for you, when you're using the same id multiple times.
The quickest fix would be to change #meatballsDelete to .meatballsDelete, and add the meatballsDelete class to your button, that way clicking will register on both buttons. Also add the $row['cid'] value as attribute to the button and then grab that with $(this).attr("myAttribute") in the function in click, which will always guarantee that the id is returned which belongs to the button.
Like #u_mulder says in the comments, you're also using an id to register the click, which will also bind to the first element with that id.
A reasonably easy way to modify your code to resolve this issue would be to get rid of the hidden cid input and add the cid value as a data value to your button. You also need to change the button to have a class meatballsDelete rather than an id, since id values must be unique. So change this:
echo "<input type = 'hidden' id = 'cid' value = '".$row['cid']."'>";
echo "<button class = 'btn' type = 'submit' id = 'meatballsDelete'>Delete</button>";
To
echo "<button class = 'btn meatballsDelete' type = 'submit' data-cid = '{$row['cid']}'>Delete</button>";
and then modify your javascript to add the click handler to items of class meatballsDelete (instead of id) and retrieve the cid value from the data-cid attribute:
$(document).ready(function(){
$(".meatballsDelete").click(function(){
var cid = $(this).data('cid');
$.ajax({
url: "deleteComment.php",
type: "POST",
async: false,
data: {
"cid": cid
}});
alert("Your comment has been deleted");
});
});
if(isset($_SESSION['u_id']) && $_SESSION['u_uid'] == $row['user_uid']){
echo "<br>";
echo "<p id='demo'></p>";
$commentId = $row['cid'];
echo "<input type = 'hidden' id = 'cid' value = '".$row['cid']."'>";
echo "<button class = 'btn' type = 'submit' onclick= 'deleteFunction($commentId, 1)'>Delete</button>";
}
and the script i used
<script>
function deleteFunction(cid, page){
//document.getElementById("demo").innerHTML = cid + " ----"+ page;
$.ajax({
url: "deleteComment.php",
type: "POST",
async: false,
data: {
"cid": cid,
"page": page}
});
alert("Your comment has been deleted!");
}
</script>
I have a datatable with an numeric value in the first column of the <tr><td> row.
I want to click on that row and parse this value to a PHP page in order to assign this number into a session.
I have below code snippet, but this isn't do the push.
selected is the class of the row when I click on it.
$(".selected td").click(function(parsegroupid) {
var group_id = $(this).attr('data');
$.ajax({
url: "./includes/indexPage/assign_session.php",
type: "post",
data: {
id: group_id
},
success: function(response) {
}
});
});
This is my PHP code:
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['group_id'];
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>
Below is a screenshot of the row when selected.
First, you need to check if the ajax call is made.
Based on your previous comments, it seems this is not happening.
You can try to specify the table id in your onclick event:
$("#table_id tbody").on( 'click', 'tr', function (){
var group_id = $(this).find("td:first-child").text();
$.ajax({
url: "./includes/indexPage/assign_session.php",
type: "post",
data: {
id: group_id
},
success: function(response) {
}
});
}
Make the change in your assign_session.php file your have pass the value in id and trying to access value of group_id.
Instead of $_POST['group_id'] use $_POST['id']
change the code like below
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['id']; // change
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>
If the ID is in the cell of the and not as an attribute, try this:
var group_id = $(this).html();
Go with this code.
You are posting id and group_id is your value and you added $_POST['group_id'] instead of $_POST['id'].
Hope this will helps you :)
<?php
ob_start();
if (session_id() == '') {
session_start();
}
$GrpID = $_POST['id']; // Change here
$_SESSION['grp'] = $GrpID;
ob_end_flush();
?>
I have made a simple search bar in which on every .keyup() event,an asynchronous request goes to a php file which then fills the data in the bootstrap popover.
The problem is that in the popover,the data is filled only once,i.e.,when I type the first character,after that the same data is shown even after multiple .keyup() events.
Here is the code:
HTML:
<input type="text" data-placement="bottom" id="search" name="search1" class="search-box" placeholder="Search..." title="Results"/>
AJAX:
$("#search").keyup(function(){
console.log('erer');
//var searchString = $("#search").val();
var data = $("#search").val();
console.log(data);
var e=$(this);
//if(searchString) {
$.ajax({
type: "POST",
url: "do_search.php",
data: {search:data},
success: function(data, status, jqXHR){
console.log('html->'+data+'status->'+status+'jqXHR->'+jqXHR);
e.popover({
html: true,
content: data,
}).popover('show');
},
error: function() {
alert('Error occured');
}
});
//}
});``
PHP:
$word = $_POST['search'];
//echo $word;
//$word=htmlentities($word)
$sql = "SELECT FName FROM user WHERE FName LIKE '%$word%' ";
//echo $sql;
// get results
//$sql = 'SELECT * FROM Profiles';
$end_result = '';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
#$end_result.='<li>'.$row["FName"].'</li>';
#$_SESSION['fnamer'] = $row['Fname'];
#$end_result.='<li>'.'<a href =view_search.php>'.$row["Fname"].'</a>'.'</li>';
echo '<a href =view_search.php>'.$row["FName"].'</a>';
}
#echo $end_result;
}
Even though in the success parameter of the $.ajax,the data is being printed fine,i.e.,it changes as I enter different alphabets,but the popover content does not change.
Please provide some suggestions to resolve this problem.
The popover is already shown. This is not the correct way of changing the popover content dynamically.
Your code: https://jsfiddle.net/gsffhLbn/
Instead, address the content of the popover directly:
var popover = e.attr('data-content',data);
popover.setContent();
Working solution
Fiddle: https://jsfiddle.net/gsffhLbn/1/
I am using a custom mvc framework and have added a favourite button. Once pressed this displays a 'successfully added to favourites' div, when clicked again it displays a 'successfully removed from favourites' div.
My query works fine, adding and deleting from my favourite table as it should.
What I would like to do now is change the state of the button depending on the selection. For example, if the user has the book in their favourites add btn-success class, if the user hasn't, use the btn-default class.
I'm not sure the best way to approach this. I'm new to php and js so any advice or direction is appreciated. I have tried adding toggleClass to my JS but it's not working. Do I need to perform a query/check on pageLoad?
I have included my code below for reference.
itemView.php
echo
'<td>
<button id="fav" value="'.$book->id.'" type="button" class="btn btn-default"></button>
</td>';
JS (in itemView.php)
$(document).ready(function(){
$( "#fav" ).click(function(){
book_id = $(fav).val();
$.ajax({
type: 'POST',
url: '<?php echo URL; ?>books/checkFav',
data: {book_id:book_id},
success: function () {
window.location.reload(true);
$("#fav").addClass( "btn-success" );
}//end success
});//end ajax
});
});
my checkFav function
public function checkFav($bookid,$userid)
{
$bookid=$_REQUEST['book_id'];
$userid=$_SESSION['user_id'];
$sql = "SELECT * FROM favourite WHERE book_id = :book_id AND user_id = :user_id";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
$rows_found = $query->fetchColumn();
if(empty($rows_found)) {
$sql = "INSERT INTO favourite (book_id, user_id) VALUES (:book_id, :user_id)";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
if ($query->rowCount() == 1) {
// successful add to favs
$_SESSION["feedback_positive"][] = FEEDBACK_ADDED_TO_FAVS;
return true;
}
} else {
$sql = "DELETE FROM favourite WHERE book_id = :book_id AND user_id = :user_id";
$query = $this->db->prepare($sql);
$query->bindParam(':user_id', $userid);
$query->bindParam(':book_id', $bookid);
$query->execute();
if ($query->rowCount() > 0) {
// successful remove from favs
$_SESSION["feedback_negative"][] = FEEDBACK_REMOVED_FROM_FAVS;
return true;
}
}
}
Use session variable in the ajax request script and using that session variable in page where button exist you can play with button css. for example:
Put this code where Button exists.
$css = "btn_default";
if($_SESSION['btnClicked'] == "success") {
$css = "btn_success";
}
Use $css variable in the button class like--
<button id="fav" value="'.$book->id.'" type="button" class="btn <?php echo $css?>"></button>
This session will manage in the ajax script where in you are adding and deleting favourite.
set session value
$_SESSION['btnClicked'] = 'success'
below the line
$_SESSION["feedback_positive"][] = FEEDBACK_ADDED_TO_FAVS;
and unset the session
unset($_SESSION['btnClicked']);
after the line.
$_SESSION["feedback_negative"][] = FEEDBACK_REMOVED_FROM_FAVS;