I am using jQuery autocomplete plugin to provide suggestions of names from the database. What I am trying to do is to display the information of the person once selected. Can someone give me an idea on how and where will I pass and get the id (primary key) of the selected person?
js
$('input[name="name"]').autoComplete({
minChars: 1,
source: function(term, response){
$.getJSON('names.php', { name: term }, function(data){
var arr = $.map(data, function(el) { return el });
response(arr);
});
},
onSelect: function(){
//get id -> show info
}
});
names.php
require 'con.php';
$term = $_GET['name'];
$arr = array();
$query = mysqli_query($connection,
"SELECT
id,
firstname,
middlename,
lastname
FROM mytbl
WHERE firstname LIKE '%$term%' ||
middlename LIKE '%term%' ||
lastname LIKE '%term%'");
while($row = mysqli_fetch_array($query)){
$arr[] = $row['firstname'] . " " . $row['middlename'] . " " . $row['lastname'];
}
echo json_encode($arr);
Thank you!
What you need to do is return multidimensional array from PHP script and handle it in jQuery script.
So your PHP snippet should look like this.
<?php
$arr = array();
while ($row = mysqli_fetch_array($query)) {
$name = $row['firstname'] . " " . $row['middlename'] . " " . $row['lastname'] . " " . $row['extension_name'];
$ar = array();
$ar['label'] = $name;
$ar['value'] = $name;
$ar['id'] = $row['id'];
$arr[] = $ar;
}
echo json_encode($arr);
Now jQuery code look something like this,
$('input[name="official_name"]').autoComplete({
minChars: 1,
source: function(term, response) {
$.getJSON('names.php', {
official_name: term
}, function(data) {
var arr = $.map(data, function(el) {
return el
});
response(arr);
});
},
select: function(event, ui) {
var id=ui.item.id;
console.log("Selected item ID => "+ id);
}
});
Above code returns multidimensional array with Name and ID. jQuery autocomplete expect label and/or value as key from returned array to display it in drop-down.
The label property is displayed in the suggestion listand the value will
be added into the textbox after the user selected something
from the list.
When you select any item you just have to use ui.item.id for accessing the id of the selected the item.
Related
I'm doing an input with autocomplete where my user can select multiple users from database and I want to submit those select users in my form where action goes to a php file that does a INSERT in the database.
So this is the input, I want the selected users to show up in p#selecionados but user selects one at a time:
<form id="formCriaJogo" method="post" action="./components/insert.php">
<label>Other users</label>
<input type="text" name="autor" id="autor" placeholder="Write users name" />
<div id="autorLista"></div>
<p id="selecionados"></p>
<button type="submit">Insert</button>
</form>
And this is jquery code to do the autocomplete:
$(document).ready(function() {
$('#autor').keyup(function() {
var query = $(this).val();;
if (query != '') {
$.ajax({
url: "./components/search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$("input#autor").css("margin-bottom", '0');
$("#autorLista").css("display", 'block');
$('#autorLista').fadeIn();
$('#autorLista').html(data);
},
error: function(error) {
console.log(error);
}
});
}
});
$('input#autor').on('change', function() {
alert($('input[name=autor]:checked', '#formCriaJogo').val());
});
});
Also, here is search.php that does the search:
<?php
include_once "../connection/connection.php";
if (isset($_POST['query'])) {
$link = new_db_connection();
$stmt = mysqli_stmt_init($link);
$output = '';
$input = $_POST['query'];
$query = "SELECT id_user, nome_user FROM users WHERE nome_user LIKE CONCAT(?, '%')";
mysqli_stmt_prepare($stmt, $query);
mysqli_stmt_bind_param($stmt, 's', $input);
mysqli_execute($stmt);
mysqli_stmt_bind_result($stmt, $id_user, $name_user);
mysqli_stmt_store_result($stmt);
if (mysqli_stmt_num_rows($stmt) > 0) {
while (mysqli_stmt_fetch($stmt)) {
$output .= "<input type='radio' value='" . $id_user . "' name='autor'>" . $name_user . "<br>";
}
} else {
$output .= '<p>The user your looking for doesn't exist.</p>';
}
echo $output;
}
Now the clicked input type=radio value which contains users' id and name I want the user name in p#selecionados just to show them what he selected and also send id and name of user selected when submitting my form.
You can create an array in jquery so , whenever you select an option from autocomplete box.. put that value inside that array in jquery .I have use checkbox instead of radio-button in below code and whenever user select any option that data will get inserted in array i.e:index and when insert button is clicked the selected data will get display in p#selecionados tag and also an ajax will call to send your selected data to php page.Also i have added value='" . $id_user."," . $name_user . "' you can split this using .split() with delimiter , to get both userid and username.Sample code :
var index = [];
//when check-box is changed
$('input[name=autor]').change(function() {
//checking if checkbox is check put it in array
if ($(this).is(':checked')) {
index.push($(this).val());
console.log(index)
} else {
//if uncheck remove the element from array
if ((index1 = index.indexOf($(this).val()) !== -1)) {
index.splice($.inArray(index1, index), 1);
console.log("remove");
}
}
});
//when insert button is click
$("button").click(function() {
//clear the p tag content
$("p#selecionados").html("");
for (var i = 0; i < index.length; i++) {
//append all selected check box
$("p#selecionados").append(index[i] + "<br />");
console.log("userid & username" + index[i]);
}
if (index != '') {
$.ajax({
url: "yourphp_page_name",
method: "POST",
data: {
//sending array to php
data: index
},
success: function(data) {
//do something
},
error: function(error) {
//do something
}
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user . <br/>
<input type='checkbox' value='" . $id_user."," . $name_user . "' name='autor'>" . $name_user . <br/>
<button type="submit">Insert</button> <br/><br/> Selected data :
<p id="selecionados"></p>
Then in your php side ,you need to get that array i.e : data using $_POST['data'] and then explode your array and use it as per your requirement.
I have a PHP and Javascript code that I am using for my typeahead search feature and it is working fine. But if you look at the code below, I am passing the search value, how can I grab the id and pass to the form URL?
HTML
<form method="get" class="form-inline customers" autocomplete="off" action="/customers/<?php echo id; ?> ">
<input class="customers" id="customers" type="text" name="customers">
<button type="submit" title="Search Customers"></button>
</form>
Javascript
<script>
$( document ).ready(function() {
$('input.customers').typeahead({
source: function (query, process) {
var countrycode = '<?php echo $agencyid; ?>';
return $.get('fetch_customers.php', { query: query, cc: countrycode }, function (data) {
data = $.parseJSON(data);
return process(data);
});
},
});
});
</script>
PHP
$countrycode1 = $_GET['cc'];
$sql="SELECT
first_name,
last_name,
id,
status,
agency_id
FROM customers
WHERE (agency_id = '$countrycode1') AND first_name LIKE '%".$_GET['query']."%' LIMIT 20";
$resultset = mysqli_query($conn, $sql) or die("database error:".
mysqli_error($conn));
$json = array();
while( $rowscity = mysqli_fetch_assoc($resultset) ) {
$json[] = $rowscity["first_name"];
$json[] = $rowscity["id"];
}
$output = json_encode($json);
echo $output;
mysqli_close($conn);
?>
Your PHP Script:
<?php
$countrycode1 = $_GET['cc'];
$sql = "SELECT
first_name,
last_name,
id,
status,
agency_id
FROM customers
WHERE (agency_id = '" . $countrycode1 . "') AND first_name LIKE '%" . $_GET['query'] . "%' LIMIT 1";
$resultset = mysqli_query($conn, $sql) or die("database error:" . mysqli_error($conn));
$json = array();
while ($rowscity = mysqli_fetch_assoc($resultset)) {
echo $rowscity["id"]; exit;
}
?>
Your Script can be like:
<script>
$(document).ready(function () {
$('input.customers').typeahead({
source: function (query, process) {
var countrycode = '<?php echo $agencyid; ?>';
$.get('fetch_customers.php', {query: query, cc: countrycode}, function (data) {
$('form').attr('action', '/customers/' + data);
});
},
});
});
</script>
I have two drop down list in the main page, when the user clicks on the country drop down(on change) another drop down list would be shown with the product list. This I accomplish using an ajax call (getproduts.php) from the country drop down list. The screen shots, the ajax call and the programs are attached .
The dropdown list works well and I can select the item too. The drop down list has the both the product description and the price in it.
I would like to get the price in a variable to be used in the main program when ever the user selects the option.
The sub total value(attached screen) in the main program should change with the price from the dropdown box when ever the user selects the product.
How can I achieve this?.
Ajax call
<script type="text/javascript">
function get_products()`enter code here`
{
var country = $("#country").val();
var type = $("#type").val();
var dataString = 'country='+ country + '&type=' + type;
$.ajax({
type: "POST",`enter code here`
url: "getproducts.php",
data: dataString,
success: function(html)
{
$("#get_products").html(html);
}
});
}
</script>
getproducts.php
<?php
error_reporting(1);
//print_r($_POST);
include('function/db_connect.php');
//session_start();
$price = Null;
//$items = Null;
if($_POST)
{
$var1 = $_POST['country'];
$var2 = $_POST['type'];
if ($var1 != '') {
echo "<label>Item<span style='color:red'>*</span></label><span style='color:red'></span></label><span class='address'>";
echo "<select id='items' name='items' style = 'width: 546px;' onChange='get_price(this.value)'>";
$sql = "SELECT * FROM tbl_product WHERE country_id = '$var1' AND type_id = '$var2'";
$db = new DB_CONNECT();
$result = mysql_query($sql);
$myarray = array();
echo "<option value=''>Select</option>";
while ($row = mysql_fetch_array($result)) {
$idp = $row["product_id"];
$iddes = $row["product_desc"];
$selp = $row["product_sell"];
$costp = $row["product_cost"];
echo "<option value='" . $idp . "'>" . $iddes . "==>".$selp ."</option>";
}
echo "</select><label>Item</label></span><span class='address'>";
}
echo "</div>";
echo "<br>";
echo "<div><label></label><span class='name'><button name = 'data' type ='button' onclick= 'valprice('items')'>Validate value</button></span></div>";
}
?>
Right now in your select html element, you're using onChange='get_price(this.value), this line of code only get the option value in this case only $idp = $row["product_id"];. If you want to select others field, then you need to attach those values into option itself during looping process occured. Here is the example usage.
In your option tag, change into this :
echo "<option value='" . $idp . "' data-price='" . $selp . "'>" . $iddes . "==>".$selp ."</option>";
You see i adding data-price='" . $selp . "' as a user defined attribute. This later on we fetch at onchange event.
After that, change your select HTML element onchange into this :
echo "<select id='items' name='items' style = 'width: 546px;' onChange='get_price(this)'>";
Finally, in your get_price() function tweak into this below code :
<script>
// array variable to store product details[id and price in this case]
var myProduct = [];
function getPrice(e) {
// set to empty for initial
myProduct.length = 0;
// fetch price
var price = $('option:selected', $(e)).data('price');
// fetch val ID
var valID = $(e).val();
// insert into array variable as a javascript object
myProduct.push({
ID : valID,
price : price
});
console.log(myProduct);
}
</script>
To fetch another fields, put another data-attributes like example above.
DEMO - check console to see the output
I'm using jQuery autocomplete and trying to get it to go directly to the link when I click on suggestion or press enter. Here's the code I used:
<script>
$(function() {
$( "#search" ).autocomplete({
source: 'search.php',
select: function(event, ui) {
$(this).val(ui.item.value);
$(this).parents("form").submit(); // this will submit the form.
}
});
});
</script>
Then I have my php code for search: '
if ($_POST['search'] != null) {
//die("asdf: " . $_POST['search']);
$search = $_POST['search'];
$result = mysqli_query($con,"SELECT * FROM question WHERE text LIKE '%$search%'");
while($row = mysqli_fetch_array($result)) {
$text = $row['text'];
$question_id = $row['question_id'];
//die($search . " " . $text);
if ($search == $text){
header("Location: http://localhost/showstats.php?question_id=$question_id");
die();
}
echo "<br>";
echo " <a href=\"showstats.php?question_id=" . $question_id;
echo "\">$text</a> ";
//echo "<br>";
}}
The problem is when I click on suggestion it doesn't redirect to "showstats.php?question_id=$question_id", insted give me a blank result page.
And when I insert die($search . " " . $text); inside if statement it's showing me text 2 times, so I know it enters the body of it statement.
also worth escaping your sql...
$search = $_POST['search'];
$search = mysqli_real_escape_string($search);
$result = mysqli_query($con, "SELECT * FROM question WHERE text LIKE '%$search%'") or die(mysqli_error($con));
When you select a suggestion, the event occurs in the client so this code in your PHP is not really necessary:
if ($search == $text) {
header("Location: http://localhost/showstats.php?question_id=$question_id");
die();
}
Instead, when you select a suggestion, try triggering the redirection from jQuery:
<script>
$(function() {
$( "#search" ).autocomplete({
source: 'search.php',
select: function(event, ui) {
// This will redirect you to whatever URL is in ui.item.value:
window.location = ui.item.value;
}
});
});
</script>
It is because your headers are already sent, you have started your output, hence the redirect will not work.
Try buffering your output.
On the same page I have an area to add a patient and a separate patient select menu. If a patient is added, I would like the select menu to show this new patient without refreshing the page.
The select menu is originally populated with:
<?php
$result = mysql_query("SELECT * FROM `patients` WHERE `company_id` = " . $user_data['company_id'] . " ORDER BY `patient_firstname`");
while($row = mysql_fetch_array($result)) {
echo '<option value="' . $row['patient_id'] . '">' . $row['patient_firstname'] . ' ' . $row['patient_lastname'] . '</option>';
}
?>
When the select menu is used the input fields first_name, last_name, & dob are populated using:
$('#patientselect').live('change', function() {
$.ajax({
url : 'patientget.php',
type : 'POST',
dataType: 'json',
data : $('#patientform').serialize(),
success : function( data ) {
for(var id in data) {
$(id).val( data[id] );
}
}
});
});
which retrieves the information from the patientget.php:
$patientId = $_POST['patientselect']; // Selected Patient Id
$result = mysql_query("SELECT `patient_id`, `patient_firstname`, `patient_lastname`, `patient_dob` FROM `patients` WHERE `patient_id` = $patientId");
$row = mysql_fetch_assoc($result);
$patientId = $row['patient_id'];
$patientFirstName = $row['patient_firstname'];
$patientLastName = $row['patient_lastname'];
$patientDob = $row['patient_dob'];
$arr = array(
'input#patient_id' => $patientId,
'input#patient_firstname' => $patientFirstName,
'input#patient_lastname' => $patientLastName,
'input#patient_dob' => $patientDob);
echo json_encode( $arr );
?>
This is my first post, so please let me if I need to provide more/clearer information.
Thank in advance!! Adam