What I need to know how to clear the textbox if the user type only 1 character and don't select on the list? I also have a ajax in autocomplete.php which I need to get the value send to textbox.
This what I have right now.
</script>
function changeAutoComplete (val) {
$( "#tags" ).autocomplete({
mustMatch: true,
source: 'autocomplete.php?selected='+val,
response: function(event, ui) {
if (ui.content.length === 0) {
$("#empty-message").text("No results found");
$(this).val("");
return false;
$("#empty-message").css({display:'', overflow: 'hidden'});
} else {
$("#empty-message").empty();
$("#empty-message").css({display:'none', overflow: 'hidden'});
}
}
});
}
</script>
Drop1
<?php
$mysqli = new mysqli("localhost", "root", "", "2015");
$combo = $mysqli->query("SELECT * FROM category GROUP BY cat_code ORDER BY id");
$option = '';
while($row = $combo->fetch_assoc())
{
$option .= '<option value = "'.$row['cat_code'].'">'.$row['category'].'</option>';
}
?>
<select id="main" name="main" onchange="changeAutoComplete(this.value)">
<option value="" selected="selected">Choose</option>
<?php echo $option; ?>
</select>
<div class="demo-frame">
Tags
<input id="tags" name="items">
<div id="empty-message" style="display:none;"></div>
</div>
autocomplete.php
<?php
$mysqli = new mysqli("localhost", "root", "", "2015") or die("Database Error");
$auto = $mysqli->real_escape_string($_GET["term"]);
$selected = $mysqli->real_escape_string($_GET["selected"]);
$sql = $mysqli->query("SELECT * FROM code WHERE item LIKE '%$auto%' AND cat_code='$selected' GROUP BY id ORDER BY item" );
if($sql)
{
$str = array();
while($row=mysqli_fetch_array($sql))
{
$str[] = $row['item'];
}
echo json_encode($str);
}
?>
In your case it better to do this with blur event. Here go with this
$('#tags').on('blur', function () {
if ($(this).val().length === 1) { //check for no. of characters entered
$(this).val(''); // clear the textbox
}
});
JSFiddle
Updates:
As from your comments, it would be better to go with change event,
change: function (event, ui) {
if (!ui.item) {
$(this).val("");
$('#empty-message').show();
} else {
$('#empty-message').hide();
}
}
JSFiddle
Related
I have implemented autocomplete search bar for my website. I will select location in the index.php page. The selected location from index.php page has to reflect to mydealers.php page also. but its not happening. instead it's showing some other location name.
Html Code
<div style=margin-left:500px;margin-top:-40px;width:500px>
<?php
echo " <select data-live-search='true' data-live-search-style='startsWith' class='selectpicker' id='locName'>";
$stmt = $conn->prepare('SELECT LocationName From arealistmain');
$stmt->execute();
while($row = $stmt->fetch()) {
echo " <option>" .$row['LocationName'] . "</option>";
}
echo "</select>";
?>
</div>
Java Script
<!--AutoComplete Search bar-->
$(function() {
$("#locName").autocomplete({
minLength: 1,
function(event) {
var value = event.getAttribute('value')
var locName = document.getElementById("locName").value;
if (value.includes('&')) {
value = value.replace("&", "%26");
}
if (locName == "") {
alert("Please Select your Location");
} else {
window.location = "http://www.citycontact.in/MyDealers.php?id="+value+"&locName="+locName;
}
return false;
}
});
});
<!--Auto Complete For Categories-->
function Demo(anchor) {
var value = anchor.getAttribute('value')
var locName=document.getElementById("locName").value;
if(value.includes('&')){
value = value.replace("&", "%26");
}
if(locName==""){
alert("Please Select your Location");
} else {
window.location = "http://www.citycontact.in/MyDealers.php?id="+value+"&locName="+locName;
}
}
here in my code i am trying to fetch and display the data after selecting a option from the dropdown using onChange, fetching data from a PHP file and via ajax displaying it in textarea in same select.php file but unfortunately it is not working out for me am quit confused were i made a mistake, please help me out on this.
select.php
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#channel").change(function(){
$.post("ajax.php", { channel: $(this).val() })
.success(function(data) {
$(".result").html(data);
});
});
});
</script>
</head>
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" id = 'channel' name="ProductCategoryID" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="1234">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group result"></div>
ajax.php
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode = '$channel' ";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
while($row = mysql_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
Try using:
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
May be it would help
replace,
$.post("ajax.php", { channel: $(this).val() })
with
$.post("ajax.php", { 'channel': $(this).val() })
$.post("ajax.php", { channel: $(this).val() },function(data) {
$(".result").html(data);
});
Please remove .success(function(data){ }) from the code and it will work :)
Try to initiate $msg first and use mysqli module.
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode =$channel";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
UPDATE
Update your post request with:
$.post("ajax.php",
{ channel: $(this).val() },
function(data) {
$(".result").html(data);
}
);
OR
$.post("ajax.php",
{ channel: $(this).val() },
successCallback
);
function successCallback(data){
//process data..
}
see https://api.jquery.com/jquery.post
here is my html:
<?php echo ($row['status'] == 1)? ?>
<span id='slide_".$row['id']."' name="slid_id" class='label label-danger'>Inactive</span>
<?php : ?>
<span id='slide_".$row['id']."' name="slid_id" class='label label-success'>Active</span>
<?php ; ?>
here is my jquery code:
$(document).ready(function()
{
$("span").click(function()
{
var id = $(":input[name=slide_id]").val();
alert(id);
});
});
i didn't get anything , i want to get the
ID & its dynamic generated value
of the span element and then perform some action like on click i want to change the status from active to inactive or vise versa.
thanks in advance.
var id = $(":input[name=slide_id]").attr('id'); should do the job. .val() only returns the current value of input elements.
Your HTML is missing from the question, but eliminating the colon in your jQuery selector might do the trick in selecting an input field - i.e. $("input[name=slide_id]").val().
If you want to get the ID attribute of a span element, this would work:
$('span_selector').attr('id');
okay finally i got the way to solve this things. m just sharing this if anyone have same issue one day then this might helpful.
html codes:
<tr class="tr">
<td class="td">
<div id="status">
<?php
echo ($row['status'] == 1)?
"<span id='".$row['id']."' class='label label-danger'>Inactive</span>":
"<span id='".$row['id']."' class='label label-success'>Active</span>";
?>
</div>
</td>
</tr>
my jquery code:
$(document).ready(function()
{
$("#status > span") .click(function()
{
var id = $(this).attr('id');
var tempelement = $(this);
var texts = $(this).closest(".tr").find("#texts").val();
var author = $(this).closest(".tr").find("#author").val();
var status = $(this).text();
$.ajax({
type: 'POST',
url: 'manage_feedback.php',
data: {id:id, texts:texts, author:author, status:status},
success: function(data)
{
if (data == "Active")
{
$(tempelement).removeClass("label label-danger");
$(tempelement).addClass("label label-success");
$(tempelement).html(data);
alert('status changed');
}
else if (data == "Inactive")
{
$(tempelement).removeClass("label label-success");
$(tempelement).addClass("label label-danger");
$(tempelement).html(data);
alert('status changed');
}
else
{
alert(data);
}
}
});
});
php script
//ajax status changer code
if (isset($_POST['id']) && isset($_POST['texts']) && isset($_POST['status']) && isset($_POST['author']))
{
$id = $_POST['id'];
$texts = trim($_POST['texts']);
$author = trim($_POST['author']);
$status = $_POST['status'];
$qry = "SELECT count(id) as count FROM tbl_testimonials WHERE texts = '".$texts."'
AND author = '".$author."' AND id != ".$id." ";
$sql = mysql_query($qry);
$data = mysql_fetch_assoc($sql);
if ($data['count'] == 0)
{
if($status == 'Inactive')
{
$qry = "UPDATE tbl_testimonials SET status = 0 WHERE id = ".$id." " ;
$sql = mysql_query($qry);
if($sql == 1)
{
echo 'Active';
exit;
}
}
elseif ($status == 'Active')
{
$qry = "UPDATE tbl_testimonials SET status = 1 WHERE id = ".$id." " ;
$sql = mysql_query($qry);
if($sql == 1)
{
echo 'Inactive';
exit;
}
}
}
else
{
echo "name already taken";
exit;
}
}
hope it will help someone.
I originally coded this piece to bring back a single data point. I realized I needed more fields returned with an onchange event (drop down select) and changed it to use JSON. It is not returning any data. The drop down is built dynamically through PHP when the page is first loaded. I'm new to this, so any help would be much appreciated.
Dropdown Code:
<p id="dropdown" style="DISPLAY: none" >
<?php
$query = "call test.spsMSTR_AllCatListBuild";
$stmt = $conn->query( $query );
$dropdown = "<select id='catlist' name='catlist' onchange='getval(this);'>";
$dropdown .= "\r\n<option value= 'NA'>Select Category</option>";
foreach ($stmt as $row) {
$dropdown .= "\r\n<option value='{$row['ID']}'>{$row['RPT_NAME']}</option>";
}
$dropdown .= "\r\n</select>";
echo $dropdown;
$conn = null;
?>
</p>
Ajax/JSON code:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script id="source" language="javascript" type="text/javascript">
$(document).ready(function(){
$("#catlist").change(function(){
var vid = document.getElementById("catlist").value;
$.getjson("ajax.php",
{catid:vid},
function(result){
alert(result); }
.error(function(xhr) {
alert(xhr)
})
; )
})})
</script>
PHP Code:
<?php include('./DBConfig.php'); ?>
<?php
$vid = $_GET["catid"];
$query = "SELECT RPT_NAME, ACTIVE FROM test.MSTR_REPORT_MASTER WHERE ID = $vid" ;
$stmt = $conn->query( $query );
//$result = $stmt->fetchColumn();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode($result);
?>
So, I have corrected your errors and you should have the below for it to work with no errors, unless there is something else that is causing errors.
<select id='catlist' name='catlist'>
<option value='NA'>Select Category</option>
<option value='id1'>val1</option>
<option value='id2'>val2</option>
<option value='id3'>val3</option>
</select>
$(function(){
$("#catlist").change(function() {
var sVal = $(this).val();
if (sVal !== "NA") { // I am assuming you don't want to make an ajax call when the value is 'NA'!
$.getJSON("ajax.php", {catid: $(this).val()}, function(result) {
alert(result);
});
//by the way $(this).val() = id1|id2|id3
}
});
});
Well if you format your code, you can see your problem.
$(document).ready(function() {
$("#catlist").change(function() {
var vid = document.getElementById("catlist").value;
$.getjson("ajax.php", {
catid: vid
},
function(result) {
alert(result);
}
.error(function(xhr) { //<-- error inside getJSON
alert(xhr)
});) //<-- a random )
})
})
and
You have an inline event onchange='getval(this);' but you do not have a function getval listed.
I am trying to integrate an image with movie titles in my auto-complete text-box.
For this, I have crawled list of movie titles and their poster links (link to the image of movie) in table "film_Posters" of mysql database.
Question:
Why I get null? Sorry if this question is asked many times, but I really couldn't fix it yet...
This is my php file:
<?php
if (isset($_GET['term'])){
$arr = array();
try {
$conn=new PDO('mysql:dbname=imdb;host=localhost', 'user', 'pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT DISTINCT movieName, posterLink FROM film_Posters WHERE movieName LIKE :term limit 0, 10');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
$arr[]=array('value'=>$row['movieName'],
'label'=>$row['movieName'],
'icon'=>$row['posterLink']);
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($arr);
}
?>
and this is my html/javascript file:
<!DOCTYPE html>
<html>
<head>
<link href="http://code.jquery.com/ui/1.10.4/themes/smoothness/jquery-ui.min.css" rel="stylesheet" type="text/css" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="http://code.jquery.com/ui/1.10.4/jquery-ui.min.js"></script>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<fieldset id = "q27"> <legend class="Q27"></legend>
<label class="question"> What are your favorite movies?<span>*</span></label>
<div class="fieldset content">
<div id="m_scents">
<label style="margin-bottom:10px;" for="m_scnts">
<input type="text" id="m_scnt" size="20" name="q27[]"
value="" placeholder="Enter text" />
</label>
</div>
</div>
</fieldset>
<script type = text/javascript>
(function($){
var $title = $('#m_scnt');
$(function () {
var arr = <?php echo json_encode($rows); ?>;
});
$title.autocomplete({
minLength: 2,
source: testfilmsauto.php,
focus: function( event, ui ) {
$title.val( ui.item.label );
return false;
}
});
$title.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
var $li = $('<li>'),
$img = $('<img>');
$img.attr({ //I AM NOT SURE ABOUT THIS PART
src: <?php echo $rows['posterLink']?>,
alt: <?php echo $rows['movieName']?>
});
$li.attr('data-value', item.label);
$li.append('<a href="#">');
$li.find('a').append($img).append(item.label);
return $li.appendTo(ul);
};
})(jQuery);
</script>
</body>
</html>
UPDATE:
Here is the updated php file with the answers from #meda and #marc:
<?php
if (isset($_GET['term'])){
try {
$conn=new PDO('mysql:dbname=imdb;host=localhost', 'user', 'pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT DISTINCT movieName, posterLink FROM film_Posters WHERE movieName LIKE :term limit 0, 10');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($rows);
}
?>
Now, I don't see null message any more, but auto-complete doesn't work at all.. I think the problem is related to javascript part... I really appreciate any help.
You're doing your fetch loop wrong:
while($row = $stmt->fetchAll(PDO::FETCH_ASSOC)) {
^^^^^^^^
fetchAll() returns ALL of the rows as an array of arrays, e.g.
$rows = array(
0 => array( contents of row #1)
1 => array( contents of row #2)
Which means the while() loop is utterly pointless. fetchAll will work only ONCE anyways, so there's no point in looping. All you need is
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC)
echo json_encode($rows);
And then in your client-side javascript:
text_to_display = data_from_server[0].movieName;
Here is all you need for the pdo Code:
PHP
if (isset($_GET['term'])){
$rows = array();
try {
$conn=new PDO('mysql:dbname=imdb;host=localhost', 'user', 'pass');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = 'SELECT DISTINCT movieName, posterLink
FROM film_Posters
WHERE movieName LIKE :term limit 0, 10';
$stmt = $conn->prepare($sql);
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
echo json_encode($rows);
}
As for the javascript, I don't see any request. You should be performing POST or GET ajax request, this is way it is null
jQuery:
(function($){
var $movie = $('#m_scnt');
var movies = "";
$.ajax({
dataType: "json",
url: 'auto.php',
success: function(response){
movies = response;
alert(JSON.stringify(response));
$movie.autocomplete({
minLength: 0,
source: movies,
focus: function( event, ui ) {
$movie.val( ui.item.label );
return false;
}
});
$movie.data( "ui-autocomplete" )._renderItem = function( ul, item ) {
var $li = $('<li>'),
$img = $('<img>');
$img.attr({
src: 'https://path/to/your/images/' + item.posterLink,
alt: item.label
});
$li.attr('data-value', item.label);
$li.append('<a href="#">');
$li.find('a').append($img).append(item.label);
return $li.appendTo(ul);
};
}
});
})(jQuery);