this code displays the name as i type, as i type it gives suggestion of names and when clicked on it it displays the result in the textbox.but i want to display the id related to that name from database when i clicked on that name from the dropdown option. please help
<input type="text" name="st_id" id="st_id" ><div id="txtHint" style="position: absolute; width:390px ;"></div>
ajax code:
$(document).ready(function () {
$("#st_id").keyup(function () {
var search = $(this).val();
if (search != '') {
$.ajax({
type: "POST",
url: "ajaxcode.php",
data: {search: search},
success: function (data) {
$("#txtHint").fadeIn();
$("#txtHint").html(data);
}
});
}
});
});
php code
<?php
if (isset($_POST["search"])) {
$display = '';
$q = $_POST["search"];
$stmt = $DBconnect->prepare("SELECT * FROM table1 WHERE First_name LIKE :sh ");
$stmt->bindValue(':sh', '' . $q . '%', PDO::PARAM_STR);
$stmt->execute();
$display = '<ul class="list-unstyled">';
foreach ($stmt as $row) {
if ($row) {
$display .= '<li>' . $row["First_name"] . ' ' . $row["Middle_name"] . ' ' . $row["Last_name"] . '</li>';
} else {
$display .= '<li>name not found</li>';
}
}
$display .= '</ul>';
echo $display;
}
?>
Most naive way I can come up with is adding an id to the top ul
<ul id="name_suggestion" class="list-unstyled">
and the id to the <li> tag with a data- attr
$display .= '<li data-user-id = '. $row["id"] . '>'.$row["First_name"].' '.$row["Middle_name"].' '.$row["Last_name"].'</li>';
Then add an a click listener to the li:
$('#name_suggestion li').on('click', function(e){
let val = $(this).attr('data-user-id');
$('#st_id').val(val);
});
Related
Here I have one drop down menu on which selection other dropdown changes result the id of other dropdown is "style_code". Now I also want to change image on dropdown selection, it is like when I select color from dropdown it changes sizes which is other dropdown, but I also want to change image on color selection.
<script>
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data:'id='+val,
success: function(data){
$("#style_code").html(data);
}
});
}
</script>
Here is check.php
<?php
$con=mysqli_connect("localhost","root","","db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query ="SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con,$query);
while ( ($row=mysqli_fetch_array($results))){?>
<option value="<?php echo $row["color_name"]; ?>">
<?php echo $row['size'] ; ?>
</option>
<?php
}
}
?>
Your difficulty comes from the fact that you are returning HTML code from the PHP script. My advice is to return JSON data then generate style_code children with jQuery.
It would be something like that :
check.php
<?php
$con = mysqli_connect("localhost", "root", "", "db") or die(mysql_error());
if(!empty($_POST["id"])) {
$query = "SELECT * FROM stylecolor WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
$data = new stdClass(); // This object will carry the results
while (($row = mysqli_fetch_object($results))) {
$data->option[] = $row;
}
// Another query to get the image name
$query = "SELECT name FROM image_name WHERE color_code = '" . $_POST["id"] . "'";
$results = mysqli_query($con, $query);
if ($row = mysqli_fetch_object($results)) {
$data->image_name = $row->name;
}
header('Content-Type: application/json');
echo json_encode($data);
}
HTML & Javascript:
...
<div class="thumb-image" id="style_image" >
<img src="images/<?php echo $productimg1?>" data-imagezoom="true" class="img-responsive" alt="" />
</div>
...
<script language="javascript">
function getState(val) {
$.ajax({
type: "POST",
url: "check.php",
data: {id: val},
dataType:'json',
success: function(data) {
$("#style_code").children().remove(); // empty the dropdown
// Add new options in the dropdown from the result data
data.option.forEach(function (item) {
$("#style_code").append('<option value="' + item.color_name + '">' + item.size + '</option>');
});
// Change the 'src' attribute of the <img>
$("#style_image").find('img').attr('src', 'images/' + data.image_name + '?d=' + Date.now().toString());
}
});
}
</script>
I have the following setup of a dynamic select options for Country, State and City using php and jquery ajax.
But the problem with this setup is, if two or more of the states have the same name, all of their associated cities become the output irrespective of country.
Like the image below (please imagine Canada has a state named California for the sake of this example):
How can I solve this problem, that is how can I get the output of Cities of State California of Country USA?
These are the sections I guess I need to improve. I have been trying a few methods but none of them is working. So I'll really appreciate any help.
The ajax:
$('.action').change(function() {
if ($(this).val() != '') {
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if (action == "country") {
result = 'state';
} else {
result = 'city';
}
$.ajax({
url: "fetch.php",
method: "POST",
data: {
action: action,
query: query
},
success: function(data) {
$('#' + result).html(data);
}
})
}
});
And the php query I have tried:
$query = "SELECT city FROM country_state_city WHERE state = '" . $_POST["query"] . "'";
$result = mysqli_query($connect, $query);
$output.= '<option value="">Select City</option>';
while ($row = mysqli_fetch_array($result))
{
$output.= '<option value="' . $row["city"] . '">' . $row["city"] . '</option>';
}
This is the full code in case you need to have a look:
index.php
<?php
$country = '';
$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$country .= '<option value="' . $row["country"] . '">' . $row["country"] . '</option>';
}
?>
<select name="country" id="country" class="form-control action">
<option value="">Select Country</option>
<?php echo $country; ?>
</select>
<select name="state" id="state" class="form-control action">
<option value="">Select State</option>
</select>
<select name="city" id="city" class="form-control">
<option value="">Select City</option>
</select>
<script>
$(document).ready(function () {
$('.action').change(function () {
if ($(this).val() != '')
{
var action = $(this).attr("id");
var query = $(this).val();
var result = '';
if (action == "country")
{
result = 'state';
} else
{
result = 'city';
}
$.ajax({
url: "fetch.php",
method: "POST",
data: {action: action, query: query},
success: function (data) {
$('#' + result).html(data);
}
})
}
});
});
</script>
And the fetch.php
<?php
if (isset($_POST["action"])) {
$output = '';
if ($_POST["action"] == "country") {
$query = "SELECT state FROM country_state_city WHERE country = '" . $_POST["query"] . "' GROUP BY state";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select State</option>';
while ($row = mysqli_fetch_array($result)) {
$output .= '<option value="' . $row["state"] . '">' . $row["state"] . '</option>';
}
}
if ($_POST["action"] == "state") {
$query = "SELECT city FROM country_state_city WHERE state = '" . $_POST["query"] . "'";
$result = mysqli_query($connect, $query);
$output .= '<option value="">Select City</option>';
while ($row = mysqli_fetch_array($result)) {
$output .= '<option value="' . $row["city"] . '">' . $row["city"] . '</option>';
}
}
echo $output;
}
?>
You need populate next selects for all filled selects before and build right query for data.
#Example for populate CITY you need to know which are COUNTRY and STATE was selected.
PHP
if(isset($_POST['country']) && $_POST['country'] != ''
&& (!isset($_POST['state']) || $_POST['state'] == '') {
// return STATES for selected COUNTRY
$sql = "SELECT country, state FROM tbl WHERE country = {postCountry}";
}
else if(isset($_POST['country']) && $_POST['country'] != ''
&& isset($_POST['state']) && $_POST['state'] == '') {
// return CITIES for selected COUNTRY and STATE
$sql = "SELECT country, state, city FROM tbl WHERE country = {postCountry} AND state = {postState}";
}
This query
$query = "SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC";
can be changed to DISTINCT
$query = "SELECT DISTINCT country FROM country_state_city ORDER BY country ASC";
JQUERY
Is good approach to wrap data into form because it provides easy work with form elements like selects.
$('.action').change(function() {
var formValues = $(this).closest('form').serialize();
$.ajax({
url: "fetch.php",
method: "POST",
data: formValues,
success: function (data) {
$('#' + result).html(data);
}
});
});
You can check DevTools Console on change and XHR request in Network in demo which values are sent in request to PHP.
DEMO JQUERY
Hope this help.
Happy coding
So I've got 2 boxes. On the left I have a list of items pulling from the database which I can drag and drop to the right. This works great. I can't for the life of me work out how to get it to post the data for the list on the right and I think I've tried every example Google has to offer this week.
When I do a print_r($_POST); on the page this submits to, I get Array ( ) with nothing in it. It doesn't seem to be grabbing the ID's and serializing them.
Does anyone have experience with this see anything I'm missing?
<script>
$(function() {
$( "ul.droptrue" ).sortable({
connectWith: "ul"
});
$( "ul.dropfalse" ).sortable({
connectWith: "ul",
dropOnEmpty: true
});
$( "#sortable1, #sortable2" ).disableSelection();
});
$( "#sortable2" ).sortable({
axis: 'y',
handle : '.handle',
update: function (event, ui) {
var data = $(this).sortable('serialize');
console.log(data);
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: 'setlists-edit-process.php'
});
}
});
</script>
<ul id="sortable1" class="droptrue">
<?php
$_GET['setlist_id'];
$sql = "SELECT material_id, material_name FROM material WHERE user_id=$session_id";
$result = mysqli_query($conn, $sql);
if (!$result) {
printf("Error: %s\n", mysqli_error($conn));
exit();
}
while($row = mysqli_fetch_array($result))
{
echo "<li id=" . $row['material_id'] . ">" . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
?>
</ul>
<ul id="sortable2" class="dropfalse">
</ul>
Replace this:
while($row = mysqli_fetch_array($result))
{
echo "<li id=" . $row['material_id'] . ">" . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
with:
while($row = mysqli_fetch_array($result))
{
echo '<li id="material_' . $row['material_id'] . '">' . $row['material_id'] . " | " . $row['material_name'] . "</li>";
}
Sortable expects the ID to be in the format setname_number.
Moreover, your code outputs in the format id=abc (no quotations), and rather it should be id="abc" with surrounding quotes.
This is the first time i am working on php and JavaScripts ... need your help in fixing something.
my site have a searchbox at the header, when a search term is submitted it goes to the search.php which holds a filter menu and search result. The filter menu is based on few selectlist. As soon as any optionis clicked in the filter menu it updates the search result.
For this i am using a javascript that calls data from another php file "SearchResult.php" to update a div with ID #Result.
PROBLEM:
it works perfectly fine at localhost however when online it causes a delay in updating the Search Result.
HELP:
Is there any way to show loading of some kind to let the viewer understand or is there anyway to make it fast.
here are my codes:
Java Script Function
function get()
{
$('#Search_Results').hide();
$.post('SearchResults.php', { Search: form.Search.value, cat: form.category.value, brand: form.brand.value },
function(output)
{
$('#Search_Results').html(output).show();
}
)
}
SEARCH FILTER FORM
enter code hereif(!empty($_REQUEST['Search'])){
$SearchTerm = $_REQUEST['Search'];
} else {
$SearchTerm = '';
}
// Search term submited
echo '<input name="Search" type="hidden" value="'.$SearchTerm.'" />';
$sql = mysql_query ("SELECT * FROM categories");
echo '<h4>Filter Categories</h4><select name="cat" onChange="get();" size="15">';
echo '<option value="" class="Select_Options">All Categories</option>';
while ($row = mysql_fetch_array($sql))
{
echo '<option class="Select_Options" value="' . $row["CategoryID"] . '">' . $row["CategoryName"] . '</option>';
}
echo '</select>';
//Few more such filters
SEARCH RESULT PAGE
if(!empty($_REQUEST['Search'])){
$SearchTerm = $_REQUEST['Search'];
}
else {
echo 'Please enter search keyword(s)';
exit();
}
if(!empty($_REQUEST['cat'])){
$cat = $_REQUEST['cat'];
$SearchQuery .= " AND categories.CategoryID = '$cat'";
}
if(!empty($_REQUEST['brand'])){
$brand = $_REQUEST['brand'];
$SearchQuery .= " AND brands.BrandID = '$brand'";
}
$sql = "SELECT DISTINCT products.ProductID, ProductKeywords, products.SectionID, products.ProductThumb, products.ProductPrice, products.CategoryID, products.SubCategoryID, products.BrandID, brands.BrandLogo, ProductTitle AS title FROM products
INNER JOIN brands ON products.BrandID = brands.BrandID
INNER JOIN sections ON products.SectionID = sections.SectionID
INNER JOIN categories ON products.CategoryID = categories.CategoryID
INNER JOIN subcategory ON products.SubCategoryID = subcategory.SubCatID $ColorJoin
WHERE MATCH (ProductKeywords) AGAINST ('$SearchTerm*' in boolean mode)$SearchQuery";
$query = mysql_query($sql);
echo '<div id="Product_Search_Container"><ul>';
while ($row = mysql_fetch_array($query))
{
$ProductID = $row["ProductID"];
$sql2 = mysql_query ("SELECT COUNT(ProColorID) AS ProductCount FROM productcolors WHERE ProductID = '$ProductID'");
while ($row5 = mysql_fetch_array($sql2))
{
$BrandID = $row["BrandID"];
$sql3 = mysql_query ("SELECT * FROM brands WHERE BrandID = '$BrandID'");
while ($row6 = mysql_fetch_array($sql3))
{
$ProductThumb = $row["ProductThumb"];
if ($ProductThumb == NULL) { $ProductThumb = "No_Image.jpg"; }
echo '<li><img src="images/Products/Thumbs/' . $ProductThumb . '" width="210px" height="275px" />
<div class="zoomer"><span class="zoom';
if ($ProductThumb != "No_Image.jpg") {
echo ' cursonstyle" style="position: relative; overflow: hidden;"><img src="images/Products/Thumbs/zoom/' . $ProductThumb . '" alt="' . $row["title"] . '" />
'; } else { echo '">'; }
echo '</span><span class="Pro_Title">' . $row["title"] . '</span>
<span class="BrandLogo"><img src="images/Brands/' . $row6["BrandLogo"] . '" /></span>
<span class="ProColors">' . $row5["ProductCount"] . ' Colors</span>
<span class="ProPrice">$' . $row["ProductPrice"] . '</span>
</a></li>';
}
}
}
echo '</ul></div>';
You could show a loading message as simple as showing it when you start the post request and hiding it in the callback.
function get()
{
$('#Search_Results').hide();
$('#loading').show().html('Please wait while loading..'); // <-- show message on function call
$.post('SearchResults.php', { Search: form.Search.value, cat: form.category.value, brand: form.brand.value },
function(output)
{
$('#loading').hide(); // <-- hide in callback function
$('#Search_Results').html(output).show();
}
)
}
You should also handle errors in your ajax request and look into prepared statements or at least use mysql_real_escape_string() for all user inputs.
I have javascript as follows :
<script type="text/javascript">
function lookup(inputString) {
if(inputString.length == 0) {
$('#suggestions').hide();
} else {
$.post("./index.php?menu=getmyFavList&ajax=ajax"
, {queryString: ""+inputString+""}
, function(data){
if(data.length >0) {
$('#suggestions').show();
$('#autoSuggestionsList').html(data);
}
});
}
}
function fill(thisValue) {
$('#inputString').val(thisValue);
setTimeout("$('#suggestions').hide();", 200);
}
</script>
And my corresponding php code is
$sql = "SELECT
u.UM_index
, u.UM_first_name
, u.UM_last_name
, p.bz_pro_city
, p.bz_pro_country
FROM
tbl_user_master As u
, tbl_profile AS p
WHERE
u.UM_index = p.bz_pro_id
AND
UM_first_name LIKE '%" . $q . "%'
AND
UM_is_active = 'yes'
";
$res = mysql_query($sql) or die("unable to execute query");
while($row = mysql_fetch_array($res))
{
echo '<li onClick="fill(\''.$row['UM_first_name']
. ' ' . $row['UM_last_name'] . '\');">'
. $row['UM_first_name']
. ' ' . $row['UM_last_name']
. ',' . $row['bz_pro_city']
. '</li>';
}
And the HTML for is like :
<input type="text" name="reciever_name" size="37" id="inputString" onkeyup="lookup(this.value)" onblur="fill()" />
Now my problem is I need to pass the index of the selected user which is in tbl_user_master. How can I do this (of course hiding the index from the sender)?
Why not put the index in an <input type="hidden"> and add it to your querystring?
Edit
What you need to do is change what happens when a user selects an item.
In your while you'll need to change the echo to
echo "
<li onclick=\"fill('{$row['UM_first_name']} {$row['UM_last_name']}'
, '{$row['UM_index']}')\">
{$row['UM_first_name']} {$row['UM_last_name']}, {$row['bz_pro_city']}
</li>"
And change your JavaScript fill function to
function fill(thisvalue, thisid){
$('#inputString').val(thisValue);
$('#selectedID').val(thisid);
setTimeout("$('#suggestions').hide();", 200);
}
You'll also need to add
<input type="hidden" name="thisid" id="thisid" value=""/>
When the form is submitted, you would access the ID of the selected item using $_POST['thisid']