jQuery Autocomplete with dynamic rows - php

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>

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);
}

Show image after select: function(event, ui)

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);

monitor and update variable number of fields in php form

I have an inventory form that pulls a variable number of rows of items from a database and creates a table/list of them, with input text boxes for quantity of cases( of 12) and individual items, and the script updates the total box with the sum of those two. I have it working if I put discrete sections of code in for each row, and have tried many while/for loops and the problem I think is the function is inside the loop and stops it from working. I looked at posts using .each() , but do not see any example that works with my setup. I went and answered a couple simple questions on here for others before posting this question, hoping to please the code gods ;-)
<form>
<div class="ex3">
<div class="headrow">
<div class="column">Batch</div>
<div class="column">Name</div>
<div class="column">UPC</div>
<div class="column">Cases</div>
<div class="column">Bottles</div>
<div class="column">Counted</div>
</div>
<?php
// grab all the pertinant entries from the database and create a row of entries for each one
$sql="SELECT BatchNum, BatchName, UPC FROM Batches WHERE CurrentBatch=1 AND UPC <> '' ORDER by BatchNum DESC";
$result = $mysqli->query($sql);
$numrows = $result->num_rows;
if ($result->num_rows > 0) {
$row_cnt = 0;
while ($row = $result->fetch_assoc()) {
echo '<div class=row>';
echo '<div class=column>'.$row['BatchNum'].'</div>';
echo '<div class=column>'.$row['BatchName'].'</div>';
echo '<div class=column>'.$row['UPC'].'</div>';
echo '<div class=column> <label for="CaseCount"></label><input type="text" inputmode="numeric" pattern="^\d{1,3}$" size="4" class="form-control" id="CaseCount'.$row_cnt.'" name="CaseCount'.$row_cnt.'" value="" ></div>';
echo '<div class=column> <label for="BottleCount"></label><input type="text" inputmode="numeric" pattern="^\d{1,3}$" size="4" class="form-control" id="BottleCount'.$row_cnt.'" name="BottleCount'.$row_cnt.'" value=""></div>';
echo '<div class=column> <label for="Counted"></label><input type="text" inputmode="numeric" pattern="^\d{1,8}$" size="8" class="form-control" id="Counted'.$row_cnt.'" name="Counted'.$row_cnt.'" value="" required></div>';
$row_cnt += 1;
echo "</div>";
}
}
?>
</div>
</li>
</ul>
</div>
</form>
<script>
// monitor the case and bottle count fields and update the counted field.
$(document).ready(function() {
$('#CaseCount0, #BottleCount0').on('input', function() {
var Counted0 = 0;
var value1 = $('#CaseCount0').val();
var value2 = $('#BottleCount0').val();
var Counted0 = (value1 * 12) + (value2 * 1);
$('#Counted0').val(Counted0);
});
$('#CaseCount1, #BottleCount1').on('input', function() {
var Counted1 = 0;
var value1 = $('#CaseCount1').val();
var value2 = $('#BottleCount1').val();
var Counted1 = (value1 * 12) + (value2 * 1);
$('#Counted1').val(Counted1);
});
$('#CaseCount2, #BottleCount2').on('input', function() {
var Counted2 = 0;
var value1 = $('#CaseCount2').val();
var value2 = $('#BottleCount2').val();
var Counted2 = (value1 * 12) + (value2 * 1);
$('#Counted2').val(Counted2);
});
// might be 20-30 of these lines
});
</script>
here is a script section I have tried, but could not get to work, I do not think it is good practice for the function to be inside the loop:
var numrows = <?php echo $numrows ?>-1;
var i;
$(document).ready(function() {
for(var i = 0; i <= numrows; i++) {
$("#CaseCount"+i).on('input', function() {
this["Counted"+i] = 0;
var value1 = $("#CaseCount" + i).val();
var value2 = $("#BottleCount" + i).val();
$("#Counted"+i).val((value1 * 12)+(value2 * 1));
});
}
});

DataTables Sorting based on SQL Statement

I have a textbox for users to insert their SQL statement. I need to sort my DataTables based on the Asc and Desc in that SQL statement. When users see the datatable content it will either be in Asc or Desc depending on whatever they type in the SQL statement. How do I go about with it
<label> Query </label>
<textarea class="form-control" name="sql_input" rows="5" id="comment" placeholder="Select statement input here..."><?php if (isset($_POST['submit'])){ echo $_POST['sql_input'];} ?></textarea>
<br><label> X-Axis </label> <input type="text" name = "xaxis" class="form-control" id="xaxis" placeholder="X Axis e.g `id`" value = <?php if (isset($_POST['submit'])){ echo $_POST['xaxis'];} ?>>
<br><label> Y-Axis </label> <input type="text" name = "yaxis" class="form-control" id="yaxis" placeholder="Y Axis e.g `created_by`" value = <?php if (isset($_POST['submit'])){ echo $_POST['yaxis'];} ?>>
<table class="table table-striped table-bordered table-hover" id="dataTable_table">
<thead>
<tr>
<?php
//generate query
$query = $row['sql_statement'];
$result = $conn_temp->query($query);
while($row1 = $result->fetch_assoc())
{
foreach((array)$row1 as $key=>$val)
{
?>
<th><?php echo $key ?></th>
<?php
}
break;
}
?>
</tr>
</thead>
<tbody>
<?php
//generate query
$query = $row['sql_statement'];
$result = $conn_temp->query($query);
while($row1 = $result->fetch_assoc())
{ ?>
<tr>
<?php
foreach((array)$row1 as $key=>$val)
{ ?>
<th><?php echo $val ?></th>
<?php
} ?>
</tr>
<?php
} ?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<link href="scripts/dataTables/dataTables.bootstrap.css" rel="stylesheet">
<script src="scripts/dataTables/jquery.dataTables.js"></script>
<script src="scripts/dataTables/dataTables.bootstrap.js"></script>
<script>
$.fn.dataTable.ext.search.push(
function( settings, data, dataIndex ) {
var select_value = $('#select_value').val();
var select_column = $('#select_column').val();
var column_index = '';
//var column = data[1] || 0; // use data for the age column
if ( select_value == '' || select_column == '' )
{
return true;
}
else {
//get the column name of data table
var column = 0;
$('#dataTable_table thead tr th').each(function(){
if( $(this).text() == select_column.toString())
{
return false;
}
column = column + 1;
});
column = data[column] || 0;
if(column!==0 && column.indexOf(select_value.toString()) >= 0)
{
return true;
}
}
return false;
}
);
$.fn.dataTableExt.sErrMode = 'throw';
$(document).ready(function () {
var table = $('#dataTable_table').DataTable();
$('#select_value').keyup( function() {
table.draw();
});
});
</script>

fill 2 inputs with jquery autocomplete using mysql and php in a loop

Ok, so I'm kinda new to this.. I've googled the crud out of this and I'm just not understanding.
I have 2 inputs, description and barcode
I need to search in the description field, and autocomplete the description and barcode upon description suggestion selection.
Here is what I have so far, I cant seem to figure out how to add the php array to the Jquery
(granted no array is shown, this is my working code for a single input field)
Someone please dumb this down for me.
<?php //My Inputs (are in a loop) *** ?>
<input name="<?php echo 'ingdes'.$y ?>" type="text" value="<?php issetValue($ingdes[$y]) ?>"class="autosearch" id="<?php echo 'ingdes'.$y ?>" size="45" autocomplete='off' /> <!-- THIS IS THE DESCRIPTION -->
DESC
<input name="<?php echo 'ingcode'.$y ?>" type="text" value="<?php issetValue($ingcode[$y]) ?>" class="code" id="<?php echo 'ingcode'.$y ?>" size="12" />
BARCD <!-- THIS IS THE BARCODE -->
<?php // End My inputs ***
// My function ***
public function jsAutoSearch() { ?>
<script>
$(function() {
var availableTags = [ <?php
$query= mysql_query("SELECT * FROM $this->usernameid ORDER BY name");
while (($row = mysql_fetch_assoc($query)) !== false){
echo '"'.$row['name'].'",';}?>
/* $row['barcode1'] is the additional field I need to get working and send to the other input field */
""];
$( ".autosearch" ).autocomplete({
source: availableTags
});
});
</script>
<?php }
// End my function
My attempt at the array ********
public function jsAutoSearch() {
$return_arr = array();
$query= mysql_query("SELECT * FROM $this->usernameid ORDER BY name");
while (($row = mysql_fetch_assoc($query)) !== false){
$row_array['name'] = $row['name']; // THIS IS THE DESCRIPTION
$row_array['barcode'] = $row['barcode1']; // THIS IS THE BARCODE
array_push( $return_arr, $row_array );
} ?>
<script>
$( ".autosearch" ).autocomplete({
source: "<?php echo json_encode($return_arr),'\n'?>",
select: function (event, ui) {
var item = ui.item;
if(item) {
$(".autosearch").val(item.name); <!-- THIS IS THE DESCRIPTION -->
$(".ingcode1").val(item.barcode); <!-- THIS IS THE BARCODE -->
}
;}
})
</script>
<?php }
<?//*****************search.php*********************
$searchterm = $_GET['term'];
$return_arr = array();
$query= mysql_query("SELECT * FROM $object1->usernameid WHERE name LIKE '%$searchterm%' ORDER BY name");
while (($row = mysql_fetch_assoc($query)) !== false){
$names[] = array( name => $row['name'], barcode => $row['defcode'] ) ;
}
// Cleaning up the term
$term = trim(strip_tags($_GET['term']));
// Rudimentary search
$matches = array();
foreach($names as $name){
if(stripos($name['name'], $term) !== false){
// Add the necessary "value" and "label" fields and append to result set
$name['value'] = $name['name'];
$name['label'] = "{$name['name']}, {$name['defcode']}";
$matches[] = $name;
}
}
// Truncate, encode and return the results
$matches = array_slice($matches, 0, 5);
print json_encode($matches);?>
//********************** JQuery *****************************************
<script type="text/javascript">
$(document).ready(function(){
var ac_config = {
source: "search.php",
select: function(event, ui){
$("#ingdes<?php echo $y ?>").val(ui.item.name);
$("#ingcode<?php echo $y ?>").val(ui.item.barcode);
},
minLength:1
};
$("#ingdes<?php echo $y ?>").autocomplete(ac_config);
});
</script>

Categories