PHP Ajax Live Search Box Clickable - php

I am trying to make a live search using ajax. The search is working fine but i want it to be clickable. This is the code
<div class="box-body">
<h2>Search Database</h2>
<input class="form-control" type="text" name="search" id="search" placeholder="search our inventory">
<br>
<br>
<h2 class="bg-success" id="result">
</h2>
<script type="text/javascript">
$('#search').keyup(function(){
var search = $('#search').val();
$.ajax({
url:'searchproditem.php',
data:{search:search},
type: 'POST',
success:function(data){
if(!data.error) {
$('#result').html(data);
$('#result li').click(function(){
var res_value = $(this).text();
$('#search').attr('value', res_value);
});
}
}
});
});
</script>
<?php
include 'db/db.php';
$search = $_POST['search'];
if (!empty($search)) {
$res = $con->prep("SELECT * FROM items WHERE itemname LIKE :search ");
$res->bindValue(':search', "$search%");
$res->execute();
$count = $res->rowCount();
if (!$res) {
die('QUERY FAILED');
}
if ($count <= 0) {
echo "Sorry We dont have that item in stock";
}else{
while ($r = $res->fetch(PDO::FETCH_ASSOC)) {
$brand = $r['itemname'];
?>
<ul class="list-unstyled">
<?php
echo "<li>{$brand} in stock</li>";
?>
</ul>
<?php
}
}
}
?>

Try this for click function. To bind events with dynamically generated events, we can use following approach.
$('#result').on('click', 'li', function(){
var res_value = $(this).text();
$('#search').attr('value', res_value);
});

Related

Autocomplete search box from MySQL that displays multiple columns

I've been trying to make an autocomplete search box from a MySQL database that displays multiple columns of data when searching.(ie. Searching for an item #, at it displays the item number, manufacturer, and price)
Below is what I have currently done, which displays everything in one line separated by spaces. I would like to have a way to change the style for each column or make each result display in multiple lines if possible.
I'm a complete noob at this so any advice/resources would be awesome!
//ajax-db-search.php
<?php
require_once "db.php";
if (isset($_GET['term'])) {
$query = "SELECT DISTINCT MFG_Item_ID, MFG_Name, Price FROM H_Item_Master WHERE MFG_Item_ID LIKE '{$_GET['term']}%' LIMIT 5";
$result = mysqli_query($conn, $query);
if (mysqli_num_rows($result) > 0) {
while ($user = mysqli_fetch_array($result)) {
$res[] = $user['MFG_Item_ID'] . " " . $user['MFG_Name'] . " " . $user['Price'];
}
} else {
$res = array();
}
//return json res
echo json_encode($res);
}
?>
//in my index.php
<!-- Topbar Search Catalog -->
<form
class="d-none d-sm-inline-block form-inline mr-auto ml-md-3 my-2 my-md-0 mw-100 navbar-search">
<div class="input-group">
<input type="text" name="term" id="term" placeholder="Search Catalog" class="form-control"
aria-label="Search" aria-describedby="basic-addon2">
<div class="input-group-append">
<button class="btn btn-primary" id="benchbutton" type="Submit">
<i class="fas fa-search fa-sm"></i>
</button>
</div>
</div>
</form>
<script type="text/javascript">
$(function() {
$( "#term" ).autocomplete({
source: 'ajax-db-search.php',
});
});
</script>
You can override the default autocomplete style this way, so you can use html br tags and your own css stylesheet :
<script type="text/javascript">
$(function() {
$( "#term" ).autocomplete({
source: 'ajax-db-search.php',
select: function(event, ui) {
$("#term").val(ui.item.name);
return false;
}
})
.autocomplete("instance")._renderItem = function(ul, item) {
return $("<li class='each'>")
.append("<div class='item'><span class='upc'>" +
item.upc + "</span><br><span class='name'>" +
item.name + "</span><br><span class='price'>" +
item.price + "</span><br></div>")
.appendTo(ul);
};
});
</script>
Using the span's classes, you have full control on any attribute (upc, name and price) in CSS :
<style>
.each .item .upc{
font-style:italic;
color:blue;
}
</style>
Here is the final result :
Using this dataset :
PS : Here is how to use prepared statement to select and fetch datas from database :
if(isset($_GET['term']))
{
$term = '%' . $_GET['term'] . '%';
$sql = "SELECT * FROM items WHERE CONCAT(upc, name) LIKE ? LIMIT 5";
$stmt = $conn->prepare($sql);
$stmt->bind_param("s", $term);
$stmt->execute();
$result = $stmt->get_result();
$items = [];
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$items[] = $row;
}
}
$conn->close();
echo json_encode($items);
}

Semantic-UI Multiple selection with PHP

I want to use JS library "Semantic-UI" with my PHP code
I want to replace the ordinary select boxes with "Semantic-UI Multiple selection Dropdown"
The original PHP Code that generates the Select items:
<div class="list-group">
<h3>Material</h3>
<?php
$query = "SELECT DISTINCT(product_gender) FROM product";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="list-group-item checkbox">
<label><input type="checkbox" class="common_selector gender" value="<?php echo $row['product_gender']; ?>" > <?php echo $row['product_gender']; ?></label>
</div>
<?php
}
?>
</div>
I want to replace input with Semantic-UI :
<div class="list-group">
<h3>Gender</h3>
<select multiple="" class="label ui selection fluid dropdown">
<?php
$query = "SELECT DISTINCT(product_gender) FROM product";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="list-group-item checkbox">
<option name='gender' class="common_selector gender" value="<?php echo $row['product_gender']; ?>"><?php echo $row['product_gender']; ?></option>
</div>
<?php
}
?>
</select>
</div>
It gathers the options, But didn't post data, since the function that posts data is :
<script>
$(document).ready(function(){
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var es2 = get_filter('es2');
var bw2 = get_filter('bw2');
var tl = get_filter('tl');
var b2 = get_filter('b2');
var gender = get_filter('gender');
var material = get_filter('material');
var hinge = get_filter('hinge');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, es2:es2, bw2:bw2, tl:tl, b2:b2, gender:gender, material:material, hinge:hinge},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
});
And we get Data by this :
if(isset($_POST["gender"]))
{
$gender_filter = implode("','", $_POST["gender"]);
$query .= "
AND product_gender IN('".$gender_filter."')
";
}
if(isset($_POST["material"]))
{
So please how can I merge Semantic-UI with my code ?

PHP Ajax live search won't load

I was working on my assignment to make an ajax live search. Unfortunately, I've got an error saying 'undefined index = q'.
Here is my jquery:
<script>
$(document).ready(function(e){
$("#search").keyup(function(){
$("#here").show();
var x = $(this).val();
$.ajax({
type:'GET',
url:'index.php',
data:'q='+x,
success:function(data){
$("#here").html(data);
},
});
});
});
</script>
<input type="search" name="search" id="search">
<div id="name">
</div>
my php:
<?php
if(empty($_GET['q']))
{
$q = $_GET['q'];
$query = "SELECT * FROM info WHERE name LIKE '%$q%'";
$result = mysqli_query($conn, $query);
while($output = mysqli_fetch_assoc($result))
{
echo '<a>' . $output['name'] . '</a>';
}
}
?>
Your code is wrong. Here is a fix
<script>
$(document).ready(function(e){
$("#search").keyup(function(){
$("#here").show();
var x = $(this).val();
$.ajax({
type:'GET',
// Here we will pass the query to the php page
url:'index.php?q='+x,
// disabling the cache
cache: false,
success:function(data){
$("#here").html(data);
},
});
});
});
</script>
<input type="search" name="search" id="search">
<div id="name">
</div>
my php:
<?php
if(isset($_GET['q']))
{
$q = $_GET['q'];
// You need to sanitize the input before pass the query.
$query = "SELECT * FROM info WHERE name LIKE '%$q%'";
$result = mysqli_query($conn, $query);
while($output = mysqli_fetch_assoc($result))
{
echo '<a>' . $output['name'] . '</a>';
}
}
?>

Select results from live search ajax

I am new to this so an early sorry if my question useless... :) I want to be able to click on a result of a search output (the same as a dropdown menu except it's with a search bar) I have looked on internet but nothing could interest me. Thank you. PS: the connection of my database is in an other code but that shouldn't be useful.
Here is my code so far :
<body>
<h1>LIVE SEARCH WITH AJAX TEST</h1>
<div class="search">
<input type="search" name="search" id="recherche" class="search" onkeypress="showdiv()">
</div>
<div class="resultat" id="resultat" id="resultat" style="display: none;">
<a>Please continue typing...</a>
<br>
<br>
<br>
<br>
</div>
<script type="text/javascript">
function showdiv() {
document.getElementById("resultat").style.display = "block";
}
</script>
PHP:
<?php
include 'connect.php';
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
if (isset($_GET['motclef'])) {
$motclef = $_GET['motclef'];
$sql = "SELECT name FROM smartphone WHERE name LIKE '%" . $motclef . "%' LIMIT 5";
$result = $connect->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"] . "<br>";
}
} else {
echo "Aucun resultat trouvé pour: " . $motclef;
}
}
?>
jQuery:
$(document).ready(function(){
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#recherche').keyup(function() {
delay(function(){
var recherche = $('#recherche').val();
if (recherche.length > 1) {
$("#resultat").html("");
$.get( "fetch.php", { motclef: recherche} )
.done(function( data ) {
$("#resultat").html(data);
});
}
}, 1000 );
});
});
First-page.php
<?php
global $wpdb;
$supplier_prod_table=$wpdb->prefix.'supplier_product_post';
$sup_query=$wpdb->get_results("SELECT * FROM $supplier_prod_table");
$supp_name_chek=$user_info->user_login;
?>
<div class="form-group">
<input name="keysearch" value="<?php if($supp_name_chek!='') { echo $supp_name_chek; }?>" placeholder="name" id="keysearch" type="text" class="form-control">
<input type="hidden" value="" id="supplier_id">
<span id="loading">Loading...</span> </div>
db page
if(isset($_POST['keysearch']))
{
include('../../../../wp-load.php');
global $wpdb;
$search = $_POST['search'];
$table_name= $wpdb->prefix.'users';
$data = $wpdb->get_results("SELECT * FROM `$table_name` WHERE `user_nicename` like '%$search%' OR `display_name` like '%$search%'");
foreach($data as $key)
{
$user_id=$key->ID;
$user = new WP_User( $user_id );
$role=$user->roles[0];
if($role=='supplier'){
$username = $key->user_login;
?>
<div class="search_show" align="left" id="<?php echo $user_id ?>"><?php echo $username; ?></div>
<?php
// echo "<div class='show' onclick='select_supp()'>".$username."</div>";
}
}
}
JS Code
jQuery(document).ready(function(){
jQuery('#keysearch').on('keyup', function(){
var ajax_search_url=search_url;
var key = jQuery('#keysearch').val();
if (key && key.length > 2)
{
jQuery('#loading').css('display', 'block');
jQuery.ajax({
url : ajax_search_url,
type : 'POST',
cache : false,
data : {
keysearch : key,
},
success : function(data)
{
console.log(data)
if (data)
{
jQuery('#loading').css('display', 'none');
jQuery("#search_result").html(data).show();
}
jQuery('#search_result .search_show').click(function() {
var text = jQuery(this).text();
var sid = jQuery(this).attr('id');
jQuery('#keysearch').val(text)
jQuery('#supplier_id').val(sid);
jQuery('#search_result').fadeOut(1000);
});
}
});
}
else
{
jQuery('#loading').css('display', 'none');
jQuery('#search_result').css('display', 'none');
}
});
});

unexpected end of input php jQuery

I have written same code at one machine and it is working fine but on other machine same code is giving error unexpected end of input. This is driving me crazy as why it is happening. Anybody who can help, please. These are my files with which I am working.
edit: I am making a small online test application for learning purpose. As the test start, the first question appears, on clicking next button the url changes to what it should be but next question does not appear and the error in the console says unexpected end of input. Since all my brackets are ok, I am not able to find error. Please help!!
TestStart.php
<?php
session_start();
if(isset($_SESSION['TestId']))
{
$TestId = $_SESSION['TestId'];
}
include('Config.php');
include('Reference.php');
$query = "select * from testquestions where testid='".$TestId."'";
$res = mysql_query($query);
if(mysql_num_rows($res) > 0)
{
$z = array();
while($fetch = mysql_fetch_array($res))
{
$z[]=$fetch['QId'];
}
$y = implode(",", $z);
$_SESSION['QIds']=$z;
}
else{
echo mysql_error();
}
?>
<body>
<div class="container">
<div class="row">
<div class="col-md-12" id="resultDiv">
<div class="col-md-12" id="qtext"></div>
<div class="col-md-12">
<div class="col-md-3">
<div class="col-md-12">
<input type="radio" id="optionA"name="options" value="A"><span id="optA"></span>
</div>
<div class="col-md-12">
<input type="radio" id="optionB" name="options" Value="B"><span id="optB"></span>
</div>
</div>
<div class="col-md-3">
<div class="col-md-12">
<input type="radio" id="optionC" name="options" value="C"><span id="optC"></span>
</div>
<div class="col-md-12">
<input type="radio" id="optionD" name="options" value="D"><span id="optD"></span>
</div>
</div>
</div>
<div id="nextbuttondiv"></div>
</div>
</div>
</div>
<script>
$(document).ready(function(){
<?php
if(isset($_GET['qno'])&&isset($_GET['qindex']))
{
$qno = $_GET['qno'];
$qindex = $_GET['qindex'];
}
else{
$qno = '1';
$qindex = '0';
}
?>
var qno = <?php echo $qno;?>;
var qindex = <?php echo $qindex;?>;
var qidsarrCm = '<?php echo $y;?>';
var arrQid = qidsarrCm.split(",");
var totalQuestions = arrQid.length;
$.ajax({
type : "post",
url : "GetQuestionForTest.php",
data : {
"quId" : arrQid[qindex]
},
dataType : "json",
success : function(data){
alert('xy');
console.log(data);
$.each(data, function(){
var qText = this.questiontext;
var optionA = this.OptionA;
var optionB = this.OptionB;
var optionC = this.OptionC;
var optionD = this.OptionD;
var nxtBtn = this.NextButton;
$('#qtext').text(qText);
$('#optA').text(optionA);
$('#optB').text(optionB);
$('#optC').text(optionC);
$('#optD').text(optionD);
$('#nextbuttondiv').html(nxtBtn);
});
},
error: function(data, statusCode, xhr){
alert(statusCode);
console.log(data);
console.log(xhr);
}
});
$('input[type=radio]').on('click',function(){
$('.nxtbtn').removeAttr('disabled');
});
$('body').on('click','.nxtbtn', function(){
$.ajax({
type : "post",
url : "SaveTestAnswers.php",
data : {
"qid" : arrQid[qindex],
"ansId" : $('input[name=options]:checked').val(),
"stuId" : <?php echo $_SESSION['CurrentUser'];?>,
"testId" : <?php echo $TestId;?>
},
dataType : "json",
success : function(data){
if(data.toString() == "true"){
qindex = qindex + 1;
qno = qno + 1;
if(qno > totalQuestions){
window.location.href="TestFinish.php";
}
else{
window.location.href="TestStart.php?qno="+qno+"&qindex="+qindex;
}
}
else{
alert(data + "Please resubmit the answer");
}
},
error : function(data, statusCode, xhr){
alert(statusCode);
console.log(data);
console.log(xhr);
}
});
});
});
</script>
</body>
GetQuestionForTest.php
<?php
$questionid = $_POST['quId'];
include('Config.php');
$query = "select * from questionstable where questionid = '".$questionid."'";
$result = mysql_query($query);
if(mysql_num_rows($result) > 0)
{
$someArray = [];
while($fetch = mysql_fetch_array($result))
{
array_push($someArray,[
'questiontext' => $fetch['questiontext'],
'OptionA' => $fetch['optionA'],
'OptionB' => $fetch['optionB'],
'OptionC' => $fetch['optionC'],
'OptionD' => $fetch['optionD'],
'NextButton' => '<button class="btn btn-success nxtbtn" disabled >Next</button>'
]);
}
$someJSON = json_encode($someArray);
echo $someJSON;
}
else{
echo mysql_error();
}
?>
SaveTestAnswers.php
<?php
$qid = $_POST['qid'];
$ansId = $_POST['ansId'];
$stuId = $_POST['stuId'];
$testId = $_POST['testId'];
include('Config.php');
$query = "insert into testattemptedanswers(StudentId,TestId,QuestionId,AnswerGiven) values('".$stuId."','".$testId."','".$qid."','".$ansId."')";
$res = mysql_query($query);
if($res){
echo 'true';
}
else{
echo 'false'.mysql_error();
}
?>
Missing quotes -
var qno = <?php echo $qno;?>;
var qindex = <?php echo $qindex;?>;
Change them to -
var qno = '<?php echo $qno;?>';
var qindex = '<?php echo $qindex;?>';
And here also -
data : {
"qid" : arrQid[qindex],
"ansId" : $('input[name=options]:checked').val(),
"stuId" : '<?php echo $_SESSION['CurrentUser'];?>',
"testId" : '<?php echo $TestId;?>'
},

Categories