jquery live search not working [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
hii i am creating a live search like this http://demo.phpgang.com/live-search-php-mysql-jquery/ and i am having a small problem in code this
jQuery("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
the codes are taken from here http://www.phpgang.com/how-to-integrate-live-search-in-php-and-mysql-with-jquery_309.html
Problem - The problem i am facing is that when i search something it shows results correctly but when i click on result then nothing happens i want that result in input box when i click it. thanks help needed
here is a complete code
index.php
<?php
$content ='<script type="text/javascript" src="jquery-1.8.0.min.js">
</script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
});
</script>
<style type="text/css">
.content{
width:900px;
margin:0 auto;
}
#searchid
{
width:500px;
border:solid 1px #000;
padding:10px;
font-size:14px;
}
#result
{
position:absolute;
width:500px;
padding:10px;
display:none;
margin-top:-1px;
border-top:0px;
overflow:hidden;
border:1px #CCC solid;
background-color: white;
}
.show
{
padding:1px;
font-size:15px;
height:50px;
}
.show:hover
{
background:#4c66a4;
color:#FFF;
cursor:pointer;
}
<div class="content">
<input type="text" class="search" id="searchid" placeholder="Search for
people" /><br />
<div id="result"></div>
</div>';
$pre = 1;
include("html.inc");
?>
search.php
<?php
include('db.php');
if($_POST)
{
$q = mysqli_real_escape_string($connection,$_POST['search']);
$strSQL_Result = mysqli_query($connection,"select id,name,email from seller
where name like '%$q%' or email like '%$q%' order by id LIMIT 5");
while($row=mysqli_fetch_array($strSQL_Result))
{
$username = $row['name'];
$email = $row['email'];
$b_username = '<strong>'.$q.'</strong>';
$b_email = '<strong>'.$q.'</strong>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="show" align="left">
<span class="name"><?php echo $final_username; ?></span> <br/>
<?php echo $final_email; ?><br/>
</div>
<?php
}
}
?>

There are few issues with your code. Let's start with
var $name = $clicked.find(\'.name\').html();
Here . is not a valid operator for concatenation in JS. It is used in PHP. To concatenate strings, use +.
Secondly, using \'.name.\' as input to find option. I suppose that name is already a string? You don't need extra escaping of ' unless that is part of echo in PHP. Simply use ' to start a string.
Next is:
var decoded = $("<div/>").html($name).text();
<div/> is not a valid selector. Use div simply.
Check the jsfiddle here for fixed code from your link:
https://jsfiddle.net/1mss5xwj/1/

Related

Autocomplete Arrow Key Scroll

I am making a Ajax driven live search . But now I want to click the dropdown list to fill the html textbox. How can I modify my codes to include a function where the user can scroll through the results list using the up/down arrow keys. Here is the JavaScript code.
<script type="text/javascript">
function fill(Value) {
$('#name').val(Value);
$('#display').hide();
}
$(document).ready(function() {
$("#name").keyup(function() {
var name = $('#name').val();
if (name == "") {
$("#display").html("");
} else {
$.ajax({
type: "POST",
url: "ajax.php",
data: "name=" + name,
success: function(html) {
$("#display").html(html).show();
}
});
}
});
});
and here is the code in ajax.php page
if(isset($_POST['name'])) {
$name=trim($_POST['name']);
$query=mysqli_query($con,"SELECT * FROM mobile WHERE name LIKE '%$name%' LIMIT 0,5");
echo "<ul>";
while($query2=mysqli_fetch_array($query))
{ ?>
<div class="ajaxcontainer">
<li onclick='fill("<?php echo $query2[' name ']; ?>")'>
<a href="preview.php?id=<?php echo $query2['name']; ?>">
<div class="ajaximage">
<img src="<?php echo $query2['photo'];?>">
</div>
<div class="ajaxh1">
<h1><?php echo $query2['name']; ?></h1>
</div>
</a>
</li>
</div>
<?php } } ?>
good news.. after working 3 hours.. i got the solution to ur problem. Checkout the solution. let me know if you have any problems in this solution.I
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style type="text/css">
ul{
position: absolute;
top: 5px;
left: 36px;
list-style: none;
}
li{
border: 1px solid grey;
width: 202px;
margin: 0px;
}
input{
width:200px;
}
</style>
<script>
function showHint(str){
if(str=="" || !str){
$("ul").empty();
return;
}
$.ajax({
type: "GET",
url: "gethint.php",
data: "q="+str,
success: function(html) {
var names = html.split(",");
var listItems ="";
var dropDown =$("#dropDown");
dropDown.innerHTML="";
$("ul").empty();
names.forEach(name =>{
var li = document.createElement("li");
li.appendChild(document.createTextNode(name));
dropDown.append(li);
$("li").click(function(){
$("#txt1").val($(this).text());
});
});
}
});
}
</script>
<h3>Start typing a name in the input field below:</h3>
<form action="">
<div style="position:relative">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
<ul id="dropDown"></ul>
</div>
</form>
</body>
</html>
This is my php file.
<?php
require("connection.php");
$sql ="SELECT name FROM users";
$a=array();
// OR $a=[];
$result=$conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$a[]=$row["name"];
//echo $row["name"];
}
}
else{
echo "No data to generate suggestions";
}
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
?>

How to select text and display it in another textfield using JavaScript or jQuery

I have a PHP/AJAX search script working just fine. The problem is when I type something in the text field the suggestions appear below, but they cannot be selected. In short, I want to select one of the suggestion and show the value in the search text field upon selecting it.
I have tried a solution in JavaScript, but it doesn't work. It shows an error in the console like "the select value is null".
ajax.php
<head>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
</head>
<body>
<input id="sear" autocomplete="off" type="text" name="search"
placeholder="Seaarch here" onkeyup="search(this.value)">
<div onclick="ali()" id="list" ></div>
<script>
function search(str){
if(str.length ==0){
document.getElementById("list").innerHTML="Please Enter Something";
return;}
xml=new XMLHttpRequest();
xml.onreadystatechange=function(){
if(xml.readyState==4 && xml.status==200){
document.getElementById("list").innerHTML=xml.responseText;}
}
xml.open("GET","search.php?char="+str,true);
xml.send();
}
</script>
<script>
document.addEventListener("DOMContentLoaded",function(){
function ali(){
var acs;
var x=document.getElementById("#list").select();
acs=x.value;
document.getElementById("#sear").innerHtml=acs;
}
});
</script>
</body>
search.php
<?php
$con=mysqli_connect("localhost","root","","userdiary");
$str=$_GET['char'];
$sql="SELECT * FROM `login` WHERE `user_id` LIKE '$str%' OR `user_name` LIKE
'$str%'";
$query=mysqli_query($con,$sql);
if(mysqli_num_rows($query)>0){
while($res=mysqli_fetch_assoc($query)){
echo "<option>" .$res['user_name']."</option>"."<hr>";
}
}
else{
echo "No match Found..";
}
?>
If the #sear element looks something like this once suggestions populate into it:
<div id="list">
<option>test</option>
<option>test a</option>
<option>test b</option>
</div>
then you can try this for your jQuery script:
$('#list option').on('click', function() {
$('#sear').val($(this).text());
});
You typed select in worng way. It should be something as follows:
<select onchange="ali()" id="list" ></select>
You can check this code I used it yesterday. You just have to change the name of SQL part according to your goal
Also what I give you is jQuery ui you have to add
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
and your input must have auto class
search.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '');
define('DB_NAME', 'some');
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn = new PDO("mysql:host=".DB_SERVER.";port=8889;dbname=".DB_NAME, DB_USER, DB_PASSWORD);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT Tname FROM Topic WHERE Tname LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['Tname'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
?>
and jQuery UI
$(function() {
$(".auto").autocomplete({
source: "search.php",
minLength: 1,
});
});
and css
.ui-menu .ui-menu-item a {
text-decoration: none;
display: block;
padding: 5px .4em;
line-height: 1.5;
min-height: 0;
font-weight: normal;
z-index:11;
}
ul#ui-id-1{
z-index:11;
display: none;
top: 132px;
left: 354.5px;
width: 283px;
}

how does twitter manage which tweet to delete?

Hi this might be a very general question but i am open to all suggestions. I am using php, mysql and javascript in my code. How can i manage to find which tweet my client want me to remove? I mean if a delete button near the tweet is pressed how can i determine that remove button is associated with that tweet? I tried this but i couldn't get it going and i don't know what the problem is. Any suggestions?
Thank you
$sql = "select * from $user";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {?>
<div style="border-style:solid;
border-color:black;
border-width:3px;
position:relative;
margin-left: auto ;
margin-right: auto;
width:500px;
margin-bottom:5px;
margin-top:5px;
data-tweet="<?php echo $row['tweetid']; ?>
">
<?php echo $row['tweet'];?>
<input type="submit" name="delete" value="Delete" onclick="deletetweet()">
<script type="text/javascript">
function deletetweet(){
var twtid = this.getAttribute("data-tweet");
$.ajax({
type:"POST",
url: "deletefollower.php",
data: { twtid : twtid }
});
}
</script>
</div>
And php file
<?php
start_session();
include 'connection.php';
$user =$_SESSION["myusername"];
if(isset($_POST['twtid']))
{
$uid = $_POST['twtid'];
$sql="DELETE FROM $user WHERE tweetid='$uid'";
}
?>
Put the ID in a data attribute:
<div style="border-style:solid;
border-color:black;
border-width:3px;
position:relative;
margin-left: auto ;
margin-right: auto;
width:500px;
margin-bottom:5px;
margin-top:5px;"
data-tweet="<?php echo $row['tweet_id']; ?>">
Then your event handler can access this.getAttribute("data-tweet") to get the tweet ID.

How can I pass the data back to index file?

I have an index.php file to contain the layout of my website. In the index file, I have a search form which sends data to another php file to process(action="search.php"). My problem is: I can select the data that suits the user's keyword and output it, but the output isn't with the layout, it's just text on white background. What I need to know is: How can I pass the data that I've selected back to index.php so that it can have layout? I've tried window.location and include but it didn't work. Here's my code:
<?php
$search=$_GET['search'];// name of the text field is "search"
include('connectdb.php');
$result=mysql_query("SELECT * FROM article WHERE header LIKE '%".$search."%'");
while($row=mysql_fetch_array($result))
{?>
<?php echo $row['header'];
echo $row['content'];
}
?>
Use php Header function to go back to index.php. This is a demo only. You just get the idea and design what you want.
<?php
$search=$_GET['search'];// name of the text field is "search"
include('connectdb.php');
$result=mysql_query("SELECT * FROM article WHERE header LIKE '%".$search."%'");
while($row=mysql_fetch_array($result))
{?>
header("index.php?header=".$row['header']."&content=".$row['content']);
}
?>
Then catch these details in your index file
<?php
$header=$_GET['header'];
$content=$_GET['content'];
?>
You can make something like this:
var text = $(this).val();
$.ajax({
url: "search.php",
type: "POST",
data: {search: text},
datatype: 'json',
success: function(data){
if(data){
//here you are parsing json object
var data = JSON.parse(data);
//0: Object
//header: "blablabla"
//content: "blablabla"
//1: Object
//header: "wwwwwws"
//content: "wewesssss"
//length will be equal of results amount
var length = data.length;
var li = '';
//here you are making li
for(var i = 0; i < length; i++){
li += '<li>';
li += data[i]['header'] . data[i]['content'];
li += '</li>';
}
//appending element in dom
$('ul').html(li);
}
}
});
this ajax...
$row = mysql_fetch_array($result);
$row = json_encode($row);
eco $row;
//this will return json object
//[{"header":"blablabla","content":"blablabla"},{"header":"wwwwwws","content":"wewesssss"}]
this your php
here is a simple example, you just gotta copy the exact same layout of index.php and implement it on search.php if you are selecting data from database on index.php then do the same query on search.php
style.css
.center_content{
width:500px;
height:300px;
background:yellow;
border:1px solid;
}
.right_column{
width:200px;
height:300px;
background:Red;
display:inline-block;
}
.right_column{
width:200px;
height:300px;
background:green;
display:inline-block;
}
index.php
<link type="text/css" rel="stylesheet" href="style.css">
<form method="get" action="send.php">
<input type="text" name="search" placeholder="search here">
<input type="submit" value="submit">
</form>
<div class="left_column">blah blah</div>
<div class="center_content">
put whatever you want here
</div>
<div class="right_column">blah blah</div>
search.php
<form method="get" action="">
<input type="text" name="search" placeholder="search here">
<input type="submit" name="submit" value="submit">
</form>
<div class="left_column">blah blah</div>
<div class="center_content">
<?php
if(isset($_GET['submit'])){
$search=$_GET['search'];// name of the text field is "search"
include('connectdb.php');
$result=mysql_query("SELECT * FROM article WHERE header LIKE '%".$search."%'");
while($row=mysql_fetch_array($result))
{?>
<?php echo $row['header'];
echo $row['content'];
}}
?>
</div>
<div class="right_column">blah blah</div>

dynamically creating div with dynamic content

I want to Create div dynamically with unique id.. base on id we need to get values form the database ..but here can get id but divTag.innerHTML=
not getting id to execute my sql query
please help me out
thanks in adnvce
.dynamicDiv {
width:200px;
height:100px;
border:solid 1px #c0c0c0;
background-color:#e1e1e1;
font-size:11px;
font-family:verdana;
color:#000;
padding:5px;
}
.dynamicDiv{ float:left;}
</style>
<script type="text/javascript" language="javascript">
function createDiv($id)
{
var id =$id;
var divTag = document.createElement("div");
var id =$id;
divTag.id = "div1";
divTag.setAttribute("align","center");
divTag.style.margin = "100px auto";
divTag.className ="dynamicDiv";
divTag.innerHTML = "<?php $sql =mysql_query("SELECT * FROM TABLE WHERE ID='$id'");
$res = mysql_fetch_array($sql);
print_r($res);
?>";
document.body.appendChild(divTag);
}
</script>
</head>
<body style="float:left;">
<div style="float:left;">
<b>Click this button to create div element dynamically</b>
<input id="btn1" type="button" value=
"create div" onClick="createDiv('<?php echo rand(); ?>');" />
You can not bring data from server with sending call to server, You can use jquery ajax to bring the data and pass the id to filter the data.

Categories