Add new data in Autocomplete - php

I am beginner in Jquery. I am using auto complete to suggest data to user in a form text box. Its working properly. But if a user entering a new entry or data in the text box.I need to add that data dynamically to the database by use of a pop up window. After that I need the id of the stored data, for storing the whole form data in other table.
Script:
<script type="text/javascript">
$(function() {
var availableTags = <?php include('vname.php'); ?>;
$("#vessel_name").autocomplete({
source: availableTags,
autoFocus:true,
minLength:2,
select: function(event, ui) {
$("#vessel_name").val(ui.item.value);
$("#vessel_id").val(ui.item.key);
}
});
});
</script>
php:
$connection = mysqli_connect("localhost","root","","db") or die("Error " . mysqli_error($connection));
//fetch vessel names from the vessel table
$sql = "select vessel_id,vessel_name from vessel";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
while($row = mysqli_fetch_array($result))
{
$vname = $row['vessel_name'];
$vid = $row['vessel_id'];
$vname_list[] =array("key"=>"$vid","value"=>"$vname");
}
echo json_encode($vname_list);
html:
<div class="form-group">
<label>Vessel Name</label>
<input type="text" id="vessel_name" placeholder="Vessel Name" class="form-control" name="nam">
</div>
<div class="form-group">
<label>Vessel Name</label>
<input type="text" id="vessel_id" placeholder="Vessel Name" class="form-control" name="nam">
</div>

Seems like you are doing it right.
Just grab the stored id from the form control.
$("#vessel_id").val();
you can as well keep it as an attribute:
<script type="text/javascript">
$(function() {
var availableTags = <?php include('vname.php'); ?>;
$("#vessel_name").autocomplete({
source: availableTags,
autoFocus:true,
minLength:2,
select: function(event, ui) {
$("#vessel_name").val(ui.item.value);
$("#vessel_id").val(ui.item.key).attr('data-id') = ui.item.key;
}
});
});
</script>

In while loop $vid and $vname this value not put in "". It will not enter into your database.
while($row = mysqli_fetch_array($result))
{
$vname = $row['vessel_name'];
$vid = $row['vessel_id'];
$vname_list[] =array("key"=>$vid,"value"=>$vname);
}

Related

Unable to get <li> value from php/ajax search results <ul>

I have a text field whereby a user can search for a last name. When they start typing then a search is performed on the database via php/ajax. This then displays names in an unordered list. At this point I am just trying to alert the id of that user if you click on the <li>.
PHP for the ajax call:
if ($_POST) {
$search = "{$_POST['last_name']}%";
$stmt = $link->prepare("SELECT `first_name`, `last_name`, `id` FROM `employees` WHERE `last_name` LIKE ? LIMIT 7");
$stmt->bind_param("s", $search);
$stmt->execute();
$result = $stmt->get_result();
$numRows = $result->num_rows;
if ($numRows > 0) {
echo "<ul id='myid'>";
while ($row = $result->fetch_assoc()) {
$first_name = sanitize($row['first_name']);
$last_name = sanitize($row['last_name']);
$id = sanitize($row['id']);
echo "<li data-id='$id'>" . $last_name . " , " . $first_name . "</li>";
}
echo "</ul>";
}
else {
echo "No results found";
}
$stmt->close();
}
jQuery
$(document).ready(function(){
$( "#last_name" ).focus();
$( "#last_name" ).keyup(function(){
$( "#loading" ).show();
var last_name = $( "#last_name" ).val();
if(last_name.length > 2) {
$.ajax({
type: 'POST',
url: 'functions/employee-search.php',
data: {last_name: last_name},
success: function(data) {
if(!data.error) {
$( "#result" ).html(data);
$( "#loading" ).hide();
}
}
});
}
if(last_name.length < 1) {
$( "#result" ).html("");
$( "#loading" ).hide();
}
});
$("#myid li").click(function() {
alert($(this).attr('id'));
});
});
HTML
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Employee</label>
<input type="text" class="form-control" name="last_name" placeholder="Search by surname" id="last_name" autocomplete="off">
<div style="display:none" id=loading><img src="../plugins/images/ajax-loader.gif" /></div>
<div id="result"></div>
</div>
</div>
</div>
If I understand the issue correctly you need to use data rather than attr.
If you use attr you are saying, get me the value of the id attribute but in your code the id value is actually stored in the data-id attribute.
Try changing this line:
alert($(this).attr('id'));
To this:
alert($(this).data('id'));
Or:
alert($(this).attr('data-id'));
You can read more about the data function here: https://api.jquery.com/data/
Also as you are adding elements to the DOM via AJAX the click event will work. You need to change this line:
$("#myid li").click(function() {
To this:
$("#result").on('click', '#myid li', function() {
jquery
$("#myid li").click(function() {
console.log($(this).attr('id'));
console.log($(this).data('id'))
});
HTML:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="myid">
<li id="one" data-id="1">one</li>
<li id="two" data-id="2">two</li>
<li id="three" data-id="3">three</li>
</ul>

autocomplete to enter return data into 3 fields when selected

Building a basic invoice page and I got the autocomplete working for my first input "item" and know that ajax can put the other two fields data into the input fields when I select and option. Not sure what has to be added to my code or where to go . Thanks
...
<input type="text" placeholder="Item #1" class="form-control auto" id="auto"/>
<script type="text/javascript">
$(function() {
//autocomplete
$("#auto").autocomplete({
source: "search1.php",
minLength: 1
});
});
</script>
</div>
<div class="col-md-6">
<input type="text" placeholder="Description" class="form-control" />
</div>
<div class="col-md-1">
<input type="text" placeholder="Qty." class="form-control" id="qty"/>
</div>
<div class="col-md-1">
<input type="text" placeholder="Tax" class="form-control" />
</div>
<div class="col-md-2">
<input type="text" placeholder="Item Total" class="form-control"id="itemprice"/>
</div>
...
Here is my php file:
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM items WHERE item LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['item'];
$return_arr[] = $row['description'];
$return_arr[] = $row['price'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
?>
You can handle this with the select callback for jQueries autocomplete.
select: function(event, ui) {
}
Assuming you return an array of data, just access each object within ui.item, then target the other input fields.
select: function(event, ui) {
$("#secondInput").val(ui.item.id);
$("#thirdInput").val(ui.item.value);
}
fiddle
do something like this :
$(document).on('change', '"#auto"', function(){
var id = $(this).val();
var $gty = $('#gty');
var $itemPrice = $('#itemprice');
$.ajax({
url : '/myurl/info/' + id,
type : 'POST',
success : function(data){
// fill inputs with data from ajax
$qty.val(data.something);
$itemprice.val(data.something);
}
});
edit
I don't think the other answer will work because jQUery ajax only returns an array of text / value . It will not return the qty and item price , therefore you are going to need another ajax call to get the details on the specific item that the user selected from the dropdown

Why is $("#tags").autocomplete not working with data from PHP?

<script>
<?php
mysql_connect('127.0.0.1', 'root', '') or die(mysql_error());
mysql_select_db("Project_Part1")or die("cannot select DB");
$sqlActivity = "SELECT aname FROM Activity";
$resultActivity=mysql_query($sqlActivity);
$aname = array();
while ($row = mysql_fetch_array($resultActivity)) {
$aname[] = $row;
}
?>
$(function() {
var availableTags =[ "<?php echo implode('","',$aname);?>" ];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
Not sure why
var availableTags =[ "<?php echo implode('","',$aname);?>" ];
is not working for the autocomplete.
When I use var availableTags = [ "Rock climbing","Fishing","Kayaking","Underwater bungee jumping" ]; It is fine.
I'm new on PHP. Can anyone help me on this?
Try:
<?php
$DBi = mysqli_connect($hostname, $user, $password, $database);
$aname = array();
$sqlActivity = "SELECT `aname` FROM `Activity`";
$resultActivity = mysqli_query($DBi, $sqlActivity); //Dump mysql_query for
//mysqli_query and don't
//forget the connection bit
while ($row = mysqli_fetch_array($resultActivity)) {
$aname[] = $row;
};
?>
<script>
$(function() {
var availableTags =[ "<?php echo implode('","',$aname);?>" ];
$("#tags").autocomplete({
source: availableTags
});
});
</script>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags" />
</div>
It looks like you are missing <?php right after your <script> tag. I moved the PHP SQL bit outside of your <script> tag (which should not matter but does help to keep things a little easier to read in my mind)
While you are at it, stop using mysql_ and switch over to mysqli_ functions as the former are deprecated

Twitter bootstrap typeahead return multiple values and fillup the editbox

I'm new in bootstrap and i need some help please, i want to create a typeahead drop-down that return 3 values from my mysql database when the user search for a contact name in "ContactName" TEXTBOX and fill up 3 edit box with the information of
-contact name
-Telephone Number
-email address
thanks a lot on advance for all your effort
this is the code that i try it to return one value i need to modified to return all those tree value
Now when i try to search the contact name it will return with correctly with no question to ask but i don't know how to modify the code to bring 3 value like i mention above
enter code here
**php page: Customer.php**
-------------------------------------------
<?php
$host = "localhost";
$uname = "root";
$pass = "";
$database = "db34218";
$connection=mysql_connect($host,$uname,$pass) or die("connection in not ready <br>");
$result=mysql_select_db($database) or die("database cannot be selected <br>");
if (isset($_REQUEST['query'])) {
$query = $_REQUEST['query'];
$sql = mysql_query ("SELECT ContactName, Telephone, Email FROM customer WHERE ContactName LIKE '%{$query}%'");
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
$array[] = $row['ContactName'];
}
echo json_encode ($array); //Return the JSON Array
}
?>
**html and java page and some php: Customersearch.php**
------------------------------------------------
<body>
.
.
.
<div class="row-fluid">
<div class="span4">
<label>ContactName </label>
<input type="text" name="ContactName" value="<?php echo $row_Recordset_QuoteCustomer['ContactName']?>" data-provide="typeahead" class="typeahead input-xlarge" autocomplete="off">
</div>
<div class="span2">
<label>Telephone </label>
<input type="text" name="Telephone" value="<?php echo htmlentities($row_Recordset_QuoteCustomer['Telephone'], ENT_COMPAT, 'utf-8'); ?>" class="span12">
</div>
<div class="span2">
<label>Email </label>
<input type="text" name="Email " value="<?php echo htmlentities(row_Recordset_QuoteCustomer['Email '], ENT_COMPAT, 'utf-8'); ?>" class="span12">
</div>
.........
.
.
.
.
.
.
<script src="../js/jquery.js"></script>
<script src="../js/bootstrap-transition.js"></script>
<script src="../js/bootstrap-alert.js"></script>
<script src="../js/bootstrap-modal.js"></script>
<script src="../js/bootstrap-dropdown.js"></script>
<script src="../js/bootstrap-scrollspy.js"></script>
<script src="../js/bootstrap-tab.js"></script>
<script src="../js/bootstrap-tooltip.js"></script>
<script src="../js/bootstrap-popover.js"></script>
<script src="../js/bootstrap-button.js"></script>
<script src="../js/bootstrap-typeahead.js"></script>
<script src="../js/SpecWorkPages/getItemsList.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('input.typeahead').typeahead({
source: function (query, process)
{
$.ajax(
{
url: 'Customer.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data)
{
console.log(data);
process(data);
}
});
}
});
})
</script>
</body>
</html>
<?php
mysql_free_result($RecordsetQuote);
mysql_free_result($Recordset_QuoteStatus);
mysql_free_result($Recordset_QuoteCustomer);
?>
If I'm understanding you correctly, you are getting results back but unable to populate the input fields. Although I don't use Twitter Bootstrap typeahead I do something very similar with jQuery's autocomplete feature. The code below is untested and of course you'll need to modify it for yourself but hopefully will be of some help.
See this working jsFiddle demo for something similar.
PHP
$array = array();
while ($row = mysql_fetch_assoc($sql)) {
array_push($array,array('ContactName'=>$row['ContactName'],'Telephone'=>$row['Telephone'],'Email'=>$row['Email']));
}
echo json_encode($array);
You can check what gets returned by manually entering the URL (ex: yoursite/Customer.php?query=SomeContactName). You should see something similar to this:
[{"ContactName":"Some Contact","Telephone":"5555555555","Email":"email#whatever.com"},
{"ContactName":"Some Other Contact","Telephone":"5555555555","Email":"anotheremail#whatever.com"}]
HTML/Javascript
<script>
$('input.typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: 'Customer.php',
type: 'POST',
dataType: 'JSON',
// data: 'query=' + query,
data: 'query=' + $('#contactName').val(),
success: function(data)
{
var results = data.map(function(item) {
var someItem = { contactname: item.ContactName, telephone: item.Telephone, email: item.Email };
return JSON.stringify(someItem.contactname);
});
return process(results);
}
});
},
minLength: 1,
updater: function(item) {
// This may need some tweaks as it has not been tested
var obj = JSON.parse(item);
return item;
}
});
</script>
Here are a couple other posts that you might want to take a look at How to return the response from an AJAX call? and Bootstrap typeahead ajax result format - Example

How to insert ID from Jquery UI auto complete

i make a jquery autocomplete and its data come from mysql database.now i m facing a small problem in this.
i want to show product name in autocomplete as u see in code below & its working good.but after clicking submit button i want to insert product ID instead of product NAME.Below is my code
<?php
require_once "include/config.php";
$sql_product = "select * from tbl_product";
$res_product = mysql_query($sql_product);
?>
<script>
$(function() {
var availableTags = [
<?php
while($rs_product = mysql_fetch_array($res_product))
{
$prod_name = $rs_product['prod_name'];
?>
"<?php echo $prod_name; ?>" <?php echo ", "; ?>
<?php
}
?>
];
$( "#tags" ).autocomplete({
source: availableTags
});
});
</script>
<label for="tags">Tags: </label>
<input id="tags" />
You can pass in your values to availableTags source in format like:
[{label:"Prod Name 1", value:1}, {label:"Prod Name2", value:2}]
Create a hidden input element, like
<input type="hidden" name="hidAutoComplete" value="" />
And:
$( "#tags" ).autocomplete({
source: availableTags,
select: function(event, ui) {
var selectedObj = ui.item;
$(this).val(selectedObj.label);
$('input[name="hidAutoComplete"]').val(selectedObj.value);
return false;
}
});
Hope it helps
TRY ( I assume there is prod_id column in your table )
var availableTags = [
<?php
while($rs_product = mysql_fetch_array($res_product))
{
$prod_id[] = $rs_product['prod_id'];
}
echo json_encode($prod_id);
?>
];
update
use json_encode

Categories