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);
}
Related
After selecting a user from autocomplete dropdown, the users name appears in the input field, now I want to display the users image.
The default image does change, after selection, but it wont load the user image?
I feel I am missing something from
var img = ui.item.label;
$("#pic").attr("src",img);
I saw one question similar to this on looking it up (show-image-in-jquery-ui-autocomplete), but this question does not use json.
Please help?
INDEX.PHP
<body>
<br />
<br />
<div class="container">
<br />
<div class="row">
<div class="col-md-3">
<img id="pic" src="images/default-image.png">
</div>
<div class="col-md-6">
<input type="text" id="search_data" placeholder="Enter Student name..." autocomplete="off" class="form-control input-lg" />
</div>
<div class="col-md-3">
</div>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#search_data').autocomplete({ //gets data from fetch
source: "fetch.php",
minLength: 1,
select: function(event, ui)
{
$('#search_data').val(ui.item.value);
//$("#pic").val(ui.item.img);
var img = ui.item.label;
$("#pic").attr("src",img);
},
})
.data('ui-autocomplete')._renderItem = function(ul, item){ //renders the item in a ul
return $("<li class='ui-autocomplete-row'></li>") //formats the row in css
.data("item.autocomplete", item) //auto complete item
.append(item.label)
.appendTo(ul);
};
});
</script>
FETCH.php
if(isset($_GET["term"]))
{
$connect = new PDO("mysql:host=localhost; dbname=tests_ajax", "root", "");
$query = "
SELECT * FROM tbl_student
WHERE student_name LIKE '%".$_GET["term"]."%'
ORDER BY student_name ASC
";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$total_row = $statement->rowCount();
$output = array();
if($total_row > 0)
{
foreach($result as $row)
{
$temp_array = array();
$temp_array['value'] = $row['student_name'];
$temp_array['label'] = '<img src="images/'.$row['image'].'" width="70" /> '.$row['student_name'].'';
$temp_array['img'] = '<img src="images/'.$row['image'].'" width="70" />';
$output[] = $temp_array;
}
}
else
{
$output['value'] = '';
$output['label'] = 'No Record Found';
$output['img'] = 'No Record Found';
}
echo json_encode($output);
}
?>
You're returning an entire <img> element (and additional text):
$temp_array['label'] = '<img src="images/'.$row['image'].'" width="70" /> '.$row['student_name'].'';
So when you do this:
var img = ui.item.label;
$("#pic").attr("src",img);
What you're attempting to end up with is this:
<img id="pic" src="<img src="images/someFile.jpg" width="70" /> Some Name">
Which of course is just a bunch of syntax errors.
If you just want to set the src of an existing <img> then only return that src value:
$temp_array['img'] = 'images/'.$row['image'];
And set the src to that value:
$("#pic").prop("src", ui.item.img);
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);
});
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');
}
});
});
I'm trying to populate a dropdown listbox with a set of five buttons. The first one works, however the other four do not, as of yet. If been looking around but due to inexperience I can't seem to put it together. Any help is appreciated. Thank you. Here is the code I have so far...incomplete.
mysql_select_db('Mydb');
$place = mysql_query("select * from tblRestaurants order by RestName ASC");
$cuisine = mysql_query("select * from tblCuisine order by CuisineName ASC");
$city = mysql_query("select * from tblCities order by CityName ASC");
$state = mysql_query("select * from tblStates order by StateName ASC");
$zipcode = mysql_query("select * from tblLocations order by ZipCode ASC");
while ($nt= mysql_fetch_assoc($place))
$arrData[] = $nt;
if(isset($_GET["ajax"]))
{
echo json_encode($arrData);
die();
}
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function displayPlace()
{
$.getJSON("Four.php?ajax=true", function(data) {
$.each(data, function(index, objRecord) {
var option=document.createElement("option");
option.value=objRecord.RestID;
option.text=objRecord.RestName;
$("#Doggie").append('<option value="' + objRecord.RestID + '">' + objRecord.RestName + '</option>');
});
});
}
function displayCuisine()
{
$.getJSON("Four.php?ajax=true", function(data) {
$.each(data, function(index, objRecord) {
var option=document.createElement("option");
option.value=objRecord.CuisineID;
option.text=objRecord.CuisineName;
$("#Doggie").append('<option value="' + objRecord.CuisineID + '">' + objRecord.CuisineName + '</option>');
});
});
}
</script>
<title>SEARCH</title>
</head>
<body>
<form>
<button type="button" onclick="javascript:displayPlace();">Place</button>
<button type="button" onclick="javascript:displayCuisine();">Cuisine</button>
<button type="button" onclick="javascript:displayCity();" >City</button>
<button type="button" onclick="javascript:displayState();">State</button>
<button type="button" onclick="javascript:displayZipCode();">Area</button>
<br />
<select name="Doggie" id="Doggie"></select>
<br />
</form>
</body>
</html>
Please modify your php code i have tried to explain this using some sample code
and pass one additional parameter of case in the ajax request and then it will work for you
$list['place'] = mysql_query("select * from tblRestaurants order by RestName ASC");
$list['cuisine'] = mysql_query("select * from tblCuisine order by CuisineName ASC");
foreach($list as $key=>$value){
while ($nt = mysql_fetch_assoc($list[$key]))
$list_array[$key] = $nt;
}
if(isset($_GET["ajax"]))
{
switch($_GET['case']){
case 'place':
echo json_encode($list_array['place']);
break;
case 'cuisine':
echo json_encode($list_array['cuisine']);
break;
}
die();
}
I have the following jQuery code:
$(document).ready(function(){
var ac_config = {
source: "autocomplete-delta.php",
select: function(event, ui){
$("#del_item").val(ui.item.SKU);
if ((ui.item.CASE_PRICE) != "N/A"){
$("#del_price").val(ui.item.CASE_PRICE);
} else {
$("#del_price").val(ui.item.UNIT_PRICE);
}
},
minLength:1
};
$("#del_item").autocomplete(ac_config);
});
Which works fine for one line item, basically the line item takes an item name, which is the field you type in for autocomplete and then after selecting it fills the price field with either the unit price or case price from my DB. Now I want to have 18 of these rows which I set up through php to be del_item1, del_item2 etc. and when I tried the following code, the autocomplete works and it fills in the item fine, but the price field does not fill in, any ideas...?
$(document).ready(function(){
for (var i = 1; i < 19; i++) {
var ac_config = {
source: "autocomplete-delta.php",
select: function(event, ui){
$("#del_item" + i).val(ui.item.SKU);
if ((ui.item.CASE_PRICE) != "N/A"){
$("#del_price" + i).val(ui.item.CASE_PRICE);
} else {
$("#del_price" + i).val(ui.item.UNIT_PRICE);
}
},
minLength:1
};
$("#del_item" + i).autocomplete(ac_config);
});
Here is the php file that the JS references:
<?php
require_once "/home/default/support/default.php";
$dbh = showDB ();
$cities = array();
$sth = $dbh->prepare("SELECT * FROM purchase_items");
$sth->execute();
while($row = $sth->fetch(PDO::FETCH_ASSOC)) {
$cities[]=$row;
}
$term = trim(strip_tags($_GET['term']));
$matches = array();
foreach($cities as $city){
if((stripos($city['SKU'], $term) !== false) || (stripos($city['FAMILY'], $term) !== false) || (stripos($city['DESCRIPTION'], $term) !== false)){
// Add the necessary "value" and "label" fields and append to result set
$city['value1'] = $city['SKU'];
$city['value2'] = $city['FAMILY'];
$city['value3'] = $city['DESCRIPTION'];
$city['label'] = "{$city['FAMILY']} - {$city['DESCRIPTION']} ({$city['SKU']})";
$matches[] = $city;
}
}
$matches = array_slice($matches, 0, 100);
print json_encode($matches);
And here is the html side as requested above these are the 16 line items I'm working with, inside of a for loop the counter in the loop is $d:
if($d&1) { ?>
<div id="trow">
<? } else { ?>
<div id="trow" class="none">
<? } ?>
<div id="thirds" style="text-indent:5px;">
<input type="text" name="del_item<? echo("$d");?>" id="del_item<? echo("$d");?>" class="salesinput"
placeholder="Start typing item SKU, family, description..." style="text-align:left; width:95%;" />
</div>
<div id="dollar"><span class="tdblackbigger">$ </span></div>
<div id="lfamt" style="width:15%;"><input type="text" name="del_price<? echo("$d");?>" id="del_price<? echo("$d");?>" class="salesinput" style="text-align:right; padding-right:5px;" /></div>
<div id="lfsold" style="width:15%;"><input type="text" name="del_retail<? echo("$d");?>" id="del_retail<? echo("$d");?>" class="salesinput" /></div>
<div id="dollar"><span class="tdblackbigger">$ </span></div>
<div id="lfamt" style="width:15%;"><input type="text" name="del_line<? echo("$d");?>" id="del_line<? echo("$d");?>" class="salesinput" style="text-align:right; padding-right:5px;" /></div>
</div>