jQuery autocomplete, fill multiple fields by selecting suggested option - php

I have autocomplete jQuery script working for pulling suggestions from MySQL database when typing in form fields on the page (3 input fields).
That is working fine, but what I would like is to when I select suggested option in the first field - all 3 fields should be filled.
Fields that I have right now is first name, last name, and company. When I select the first name - last name and company should be automatically filled with data.
Here's php:
<html>
<head>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function()
{
$( "#first_name" ).autocomplete({
source: 'autocomplete.php'
});
});
$(function()
{
$( "#last_name" ).autocomplete({
source: 'autocomplete.php'
});
});
$(function()
{
$( "#company" ).autocomplete({
source: 'autocomplete.php'
});
});
</script>
</head>
<body>
<div id="wrapper">
<div class="ui-widget">
<p>First name</p>
<input type="text" id="first_name">
</div>
<div class="ui-widget">
<p>Last name</p>
<input type="text" id="last_name">
</div>
<div class="ui-widget">
<p>Company</p>
<input type="text" id="company">
</div>
</div>
</body>
</html>
And here's the autocomplete.php file:
<?php
$host="localhost";
$username="user";
$password="password";
$databasename="dbname";
$connect=mysql_connect($host,$username,$password);
$db=mysql_select_db($databasename);
$searchTerm = $_GET['term'];
$select =mysql_query("SELECT * FROM jemployee WHERE first_name LIKE '%".$searchTerm."%'");
while ($row=mysql_fetch_array($select))
{
$spojeno = $row['first_name'] . ' ' . $row['last_name'] . ' ' . $row['kompanija'];
$data[] = $spojeno;
}
//return json data
echo json_encode($data);
?>
So, when the suggested option from "first_name" is selected - "last_name" and "company" should be filled with corresponding data from a database. Any suggestions?

Use something Jquery likes:
$(document).on('keyup', '#firstname', funtion(){
$.ajax({
type:"POST",
url:"ajax.php",
data:$("#firstname").val();
},
success:function (res){
$("#lastname").val(res.lastname);
$("#company").val(res.company);
},
)};
});
And PHP ajax.php file:
<?php
\\Select lastname, company with $_POST['data']
echo json_endcode($result);
Should check and handle the ajax response. If you can you this solution, please make it better.

What I did is passing the ajax "item" result as the autocomplete "value" :
It looks like this :
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Id, //the data that will be shown in the list !
value: item //item holds "Id" and "Name" properties
};
}))
}
I then subscribe the autoComplete "select" event to prevent it's default behaviour.
I then fill the different fields I need to :
select: function(event, ui){
//Update Customer Name Field on Id selection
event.preventDefault()
$("#CustomerId").val(ui.item.value.Id);
$("#CustomerName").val(ui.item.value.Name);
},
here's the entire autocomplete call, in case it helps ;)
$("#CustomerId").autocomplete({
source: function (request, response) {
$.ajax({
url: "/.../../GetAvailablePartnerInformations",
type: "POST",
dataType: "json",
data: { prefix: request.term },
success: function (data) {
response($.map(data, function (item) {
return {
label: item.Id,
value: item
};
}))
}
})
},
change: function (event, ui) {
//Forces input to source values, otherwise, clears
//NOTE : user could still submit right after typing => check server side
if (!ui.item) {
//http://api.jqueryui.com/autocomplete/#event-change -
// The item selected from the menu, if any. Otherwise the property is null
//so clear the item for force selection
$(event.target).val("");
$(event.target).addClass("is-invalid");
}
else {
$(event.target).removeClass("is-invalid");
}
},
select: function(event, ui){
//Update Customer Name Field on Id selection
event.preventDefault()
//Note : the "value" object is created dynamically in the autocomplete' source Ajax' success function (see above)
debugger;
$("#CustomerId").val(ui.item.value.Id);
$("#CustomerName").val(ui.item.value.Name);
},
messages: {
noResults: "",
results: function (resultsCount) { }
},
autoFocus: true,
minLength: 0
})

Related

Set value in select2 option by data from database

I want to make edit from. In this form contain input form control using select2 option. This select2 option input form can't display selected data that return from the database. I want to make the select2 option can be change too. I've tried this but still can display the selected data. Thank You :)
Here's my view
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
</head>
<body>
<?php echo form_open('company2/do_update') ?>
<form>
<select id="Name" class="searching form-control" style="width:500px" name="company"></select>
<button type="submit" class="btn btn-info waves-effect waves-light">Save</button>
<?php echo form_close(); ?>
</form>
</body>
<script type="text/javascript">
$('.searching').select2({
placeholder: 'Masukkan Nama Company',
ajax:{
url: "<?php echo base_url('company2/select2'); ?>",
dataType: "json",
delay: 250,
processResults: function (param) {
return {
compClue: param.term,
};
},
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.Name,
text: item.Name,
value:item.Name
});
});
return{
results: results,
cache: true,
};
}
}
});
var response = {};
response.val = "<?php echo $row['Name'];?>";
$("#searching option[value='" + response.val +"']").attr("selected","selected");
I would just output the content you want for the select to a div using PHP and then get the div content and append somewhere using javascript if needed.
<div id="selectOptions">
<?php
foreach($option as $row){
$optionVal = $row->optionVal;
$optionLabel = $row->optionLabel;
echo "<option value='$optionVal'>$optionLabel</option>";
}
?>
</div>
Since you are already using jQuery you can then get the content of the div using:
var options = $('#selectOptions').html();

Issue for autocomplete from Db

Actually, I have done location search for normal HTML input type in my site (not functionality wise), I have stored locations name in database, if I search any location it should come jQuery autocomplete also and if I click a bangalore means bangalore records will open, fetching from database how will fix and please help me anyone.
Here my HTML markup:
<div class="form-group keyword">
<input type="text" id="location" placeholder="Search by location" name="location" list="locations" class="searchlocation" />
</div>
Here my PHP code:
<?php
require_once ('config.php');
$q=$_REQUEST["q"];
$sql="SELECT `pg_address` FROM `tbl_master_property` WHERE pg_address LIKE '%$q%'";
$result = mysql_query($sql);
$json=array();
while($row = mysql_fetch_array($result)) {
$data[] = $row['pg_address'];
}
echo json_encode($data);
?>
Ajax and jQuery code:
<script type="text/javascript">
$(function() {
$( "#location" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "locationsearch.php",
dataType: "json",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
});
});
</script>

Integration for php with ajax

I have a record of carriers and clients. When selecting a carrier on the customer screen, I need it to be automatically filled out the carrier's e-mail and telephone. The PHP file is returning a JSON correctly, but it is dropping in the error of jquery and not in success. I checked in Firefox's Firebug and the HTML tab of the console, where the GET requisition is reset.
<?php
include "Config/config_sistema.php";
$res = mysql_query("SELECT * FROM transportadoras");
$menu_items = null;
while($ln = mysql_fetch_object($res)){
$menu_items[] = $ln;
}
json_encode($menu_items);
?>
<script>
$("body").on("change","#transportadoras",function(event){
event.preventDefault();
var trigger=$(this);
$.ajax ({
type: "POST",
url: "buscaDadosTransportadora.php",
dataType: 'json',
success: function (data) {
$("#telefone_transp").val(data.telefone);
$("#email_transp").val(data.email);
},
error: function (data) {
alert("Erro");
},
});
});
</script>
return in ajax
[{"ID":"5","Nome":"Vinicius","email":"viniciusbalbinot91#gmail.com","telefone":"32680018"},{"ID":"6","Nome":"teste","email":"teste#teste.com.br","telefone":"12345567"}]
You response is array .
[{"ID":"5","Nome":"Vinicius","email":"viniciusbalbinot91#gmail.com","telefone":"32680018"},....]
you should loop through data.
success: function (data) {
$.each(data,function(user){ /* code ...*/});
}
If you want some current row select one row from mysql .
hope it can help u
php.php
$inp=$_POST["data"];
$txt[0]=array("ID"=>"5","Nome"=>"Vinicius","email"=>"viniciusbalbinot91#gmail.com","telefone"=>"32680018");
$txt[1]=array("ID"=>"6","Nome"=>"teste","email"=>"teste#teste.com.br","telefone"=>"12345567");
for($c=0;$c<sizeof($txt);$c++)
{
if($txt[$c]["ID"]==$inp)
{echo json_encode($txt[$c]);}
}
index.php
ID:<input id="txt" name="txt" type="text" />
<br><br>
Name:<input id="name" name="txt0" type="text" disabled="disabled"/><br>
Email:<input id="email" name="txt0" type="text" disabled="disabled"/><br>
Tel:<input id="tel" name="txt0" type="text" disabled="disabled"/><br>
js
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("document").ready(function()
{
$("#txt").keyup(function ()
{
$.ajax(
{
type:"POST",
dataType:"json",
url:"php.php",
data:{data : $("#txt").val()},
success: function(data)
{
$("#name").val(data.Nome);
$("#email").val(data.email);
$("#tel").val(data.telefone);
},
error: function ()
{
alert("Error!");
}
});
});
});
</script>

dynamic dropdown is populated ONLY if I click on it

I have a textbox (auto-complete) where users can enter an actor/actress name which works fine.
As soon as user insert a name in the textbox, a dynamic dropdown should be populated showing list of movies by that actor.
Problem:
when user insert a name in the textbox, an empty dropdown is populated, but if user click on the dropdown or somewhere in the page, then list of movies are shown in the dropdown! Another issue is that if user press Enter inside the textbox (after he inserted the name), the textbox will be cleared!!
Could someone kindly let me know what is the problem with my code?
Here is the code:
<html>
<head>
<link type="text/css" href="res/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="res/jquery.min.js"></script>
<script type="text/javascript" src="res/jquery-ui.min.js"></script>
<script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js"type="text/javascript"type="text/javascript"></script>
</head>
<body>
<form>
<p>
<input type="textbox" name= "tag" id="tags" placeholder="Enter an actor/actress name here" />
</p>
<p>
<select id="movieName" name="movieName[]" multiple="multiple" width="200px" size="10px" style="display:none;">
</select>
</p>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
focus: function( event, ui ){
event.preventDefault();
return false;
},
select: function (event, ui){
$("#tags").on('autocompletechange change', function () {
var selectedVal = $(this).val();
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}).change();
}
});
});
</script>
</form>
</body>
</html>
and this is actions.php:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$html = "";
if(isset($_POST['q']) && !empty($_POST['q'])){
try{
include('imdbConnection.php');
$sql = $conn->prepare("SELECT DISTINCT movieName FROM cast_movie WHERE castName = :q");
$sql->execute(array(':q' => $_POST['q']));
while($rows = $sql->fetch(PDO::FETCH_ASSOC)){
$option = '<option value="' . $rows['movieName'] . '">' . $rows['movieName'] . '</option>';
$html .= $option;
}
} catch(PDOException $e){
echo 'ERROR: ' . $e->getMessage();
}
echo $html;
exit;
}
?>
this part.
$("#tags").on('autocompletechange change', function () {
var selectedVal = $(this).val();
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}).change();
Action will be made on "change". . try to change it as on "keyup"
change will only be trigger if the element loses its focus.
EDIT: you should change this part ..
$("#tags").on('autocompletechange keyup', function () {
var selectedVal = $(this).val();
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}).keyup();

php-jquery autocomplete the textbox from database

I want to auto load the text box with some database values. I tried with following code but not getting the values for autocomplete. I used firebug to debug the script but neither it is showing error nor I am getting results.
Here is the code-
<script src="js/jquery1.10.min.js"></script>
<script src="js/jquery-ui.min.js"></script>
<script>
$('#userlist').autocomplete({
source: function( request, response ) {
//alert('hi')
$.ajax({
url : 'ajax.php',//?action=getUsers',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'users'
},
success: function( data ) {
//alert('in');
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
</script>
<form action="search_result.php" name="searchform" method="post">
<input id="userlist" type="text" class="form-control txt-auto"/>
</form>
You have to wait for $('#userlist') to be created :
$(document).ready(function(){
$('#userlist').autocomplete({
// code ...
});
});

Categories