autocomplete using php and html - javascript

I want to do text autocomplete using php and html..
i have tried the below code
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj = array_unique($dna);
print_r(array_values($jj));
?>
result is
my html
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.4/
themes/smoothness/jquery-ui.css">
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.4
/jquery-ui.js">
</script>
</head>
<body>
<form name="vinform" method="get"> <input type="text" name="editor" autocomplete="on"> <input type="submit" value="Show" id="display"> </form>
<div id="div1"></div>
<script type="text/javascript">
$(function() {
$('#div1').autocomplete({
source: "auto.php"
});
});
</script>
</body>
it doesn't show the words from mysql when i type some word in the text field ..i have to show the related words from mysql based on the text field input,when i type a character in the text field..can anyone help me to solve the issue in my code?
tried with Ajax
var se = null;
$(function () {
var minlength = 1;
$("#editor").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (se != null)
se.abort();
se = $.ajax({
type: "GET",
url: "auto.php",
data: value,
dataType: "text",
success: function(msg){
if (value==$(that).val()) {
}
}
});
}
});
});
php
<?php
if(isset($_GET['editor']))
{
$con=mysqli_connect("localhost","root","admin321","data");
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$name=$_GET['editor'];
$sql = "select value from fin where value LIKE '%".$name."'";
$result = mysqli_query($connection, $sql) or
die("Error " . mysqli_error($connection));
$dna = array();
while($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
$jj=array_unique($dna);
print_r ( $jj);
}
?>
no autocomplete action

With option 1 (Jquery UI autocomplete) and try something like that
<?php
$connection = mysqli_connect("localhost", "root", "pass", "data") or die("Error " . mysqli_error($connection));
$sql = "select value from fin";
$result = mysqli_query($connection, $sql) or die("Error " . mysqli_error($connection));
$dna = array();
while ($row = mysqli_fetch_array($result))
{
$dna[] = $row['value'];
}
echo json_encode($dna);
?>
Jquery UI autocomplete state about source option
String: When a string is used, the Autocomplete plugin expects that string to point to a URL resource that will return JSON data. It can be on the same host or on a different one (must provide JSONP). The Autocomplete plugin does not filter the results, instead a query string is added with a term field, which the server-side script should use for filtering the results. For example, if the source option is set to "http://example.com" and the user types foo, a GET request would be made to http://example.com?term=foo. The data itself can be in the same format as the local data described above.

You can use AJAX and Jquery..in html code call the function on keyup event and send data using ajax request after that get data from database using LIKE query and display it..

in input add id="editor"
<input type="text" id="editor" name="editor" autocomplete="on">

Related

Is there a way to pass value of a Button on click to another php file?

My aim is to get the lec_id which is the Button value when the button is clicked and pass it to chapters.php where I use the button value for a SQL query.
Below is part of my code for index.php
<?php
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from lectures";
$result = mysqli_query($con, $query);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$lec_id = $row['lec_id'];
$lec_name = $row['lec_name'];
$lec_number = $row['lec_number'];
$lec_views = $row['lec_views'];
echo "<button id=linkButton name={$row['lec_name']} value={$row['lec_id']} type='button' class='btn btn-outline-primary lecture' onclick='buttonClicked(this)'>
{$row['lec_name']}
</button> ";
}
} else {
echo "0 results";
}
?>
my button onclick function
function buttonClicked(btn) {
btn.click_counter = (btn.click_counter || 0) + 1;
document.getElementById("num_clicks_feedback").textContent = `btn ${btn.getAttribute('name')} has been clicked ${btn.click_counter} times`;
localStorage.setItem("lecId", btn.getAttribute('value'));
location.href = 'index.php?action=lec_hub/chapters';
}
I want to use the Button value here in chapters.php for a SQL query.
<html>
<head></head>
<body>
<?php
echo "<p id='lecId'></p>";
$con = mysqli_connect("localhost", "root", "", "lectureHub");
if(!$con) {
die("Could not connect to MySql Server:" . mysqli_error());
}
$query = "select * from chapters where <<this is where i want to use lecId>> ";
?>
<script>
function getValue(){
var lecId = localStorage.getItem("lecId");
document.getElementById("lecId").innerHTML = lecId;
var resetValue= 0;
localStorage.setItem("lecId", resetValue)
}
getValue()
</script>
</body>
</html>
Welcome to Stack Overflow! As Barmar stated in their comment, you can pass data to a PHP file using URL parameters, or more commonly known as GET parameters. Here's how you do it.
From your file with your button in it, you can create a form like this one:
<form action="chapters.php" method="get">
<input type="text" name="data" /> <!-- This is the value that will be passed -->
<input type="submit" value="Button" /> <!-- This is your button -->
</form>
And then from your PHP file, you can get that passed data like this:
echo $_GET["data"]
$_GET is a global PHP array that contains all of the URL parameters sent to the file. you can pass multiple values as GET parameters to a file. You can read all about the $_GET variable here. I hope this helps!

autocomplete search box unresponsive

I made an autocomplete search box that suggests words from a mysql table column as i type but the problem is that it works only if i limit the sql query at approx 1200...and i have about 2500 records. After 1200 it becomes unresponsive. I indexed the column as FULLTEXT and here is the code i use:
The HTML:
<script type="text/javascript">
$(function() {
var availableTags = <?php include('autocomplete.php'); ?>;
$("#furnizor").autocomplete({
source: availableTags,
autoFocus:true
});
});
</script>
<input id="furnizor" type="text" size="50" />
And here is the php script 'autocomplete.php':
<?php
$connection = mysqli_connect("localhost","user","password","database") or die("Error " . mysqli_error($connection));
$sql1 = "select distinct name from search";
$result_search = mysqli_query($connection, $sql1) or die("Error " . mysqli_error($connection));
$dname_list = array();
while($row = mysqli_fetch_array($result_search))
{
$dname_list[] = $row['name'];
}
echo json_encode($dname_list);
?>
The table is named 'search' and the column i search in is named 'name'.
So all this works if i limit the sql query to 1200...everything over that number becomes unresponsive.
Is there a way to make this work for about 2500 records?

How to prevent Ajax from loading the unnecessary elements repeatedly?

I want Ajax to apply only in the div (#usersDiv)
When selector is changed into 'body' it loads the whole page repeatedly. (Cannot type in the box)
but when selector changed as #userDiv, it shows the search box twice in the page. In the first box can be typed, but again second box loads over and over.
PHP file is as follows (test.php)
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
function users($connection){
if(!empty($_POST)){
$country = $_POST['userCountry'];
$sql = "SELECT * FROM users WHERE country = '$country' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userName = $row['username'];
$city = $row['city'];
echo '<div><h4>'. $userName. " ". $city. '</h4></div>';
}
} else {
echo "Use search box!";
}
} else {
echo "Use Search Box!";
}
}
?>
<html>
<head><script src = "jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON("http://freegeoip.net/json/", function(data) {
var country = data.country_name;
$.ajax({
method:"POST",
url:"test.php",
data:{userCountry:country},
success:function(result){
$('#usersDiv').html(result);
}
});
});
});
</script>
</head>
<body>
<form name = "searchForm" action = "search.php" method = "POST">
<input type = "text" name = "searchPlace" required />
<input type = "submit" value = "Search"/>
</form>
<div id = "usersDiv"> <?php users($connection); ?> </div>
</body>
<html/>
I have altered your code to wrap your PHP function within an if($_POST) to prevent the entire page loading
<?php
$connection = mysqli_connect('localhost', 'root', '', 'users');
if($_POST){ // Check if form has been submitted
$country = $_POST['userCountry'];
$sql = "SELECT * FROM users WHERE country = '$country' ";
$result = mysqli_query($connection, $sql);
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
$userName = $row['username'];
$city = $row['city'];
echo '<div><h4>'. $userName. " ". $city. '</h4></div>';
}
} else {
echo "Use search box!";
}
}else{ // If it hasn't then show the search form
?>
<html>
<head><script src = "jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#searchForm").on("submit",function(e){ // Check for form submission
$.getJSON("http://freegeoip.net/json/", function(data) {
var country = data.country_name;
$.ajax({
method:"POST",
url:"test.php",
data:{userCountry:country},
success:function(result){
$('#usersDiv').html(result);
}
});
});
});
});
</script>
</head>
<body>
<form name = "searchForm" action = "search.php" method = "POST" id="searchForm">
<input type = "text" name = "searchPlace" required />
<input type = "submit" value = "Search"/>
</form>
<div id = "usersDiv"></div>
</body>
<html/>
<?php } ?>
As Alexander suggests, read up on SQL Injection
How can I prevent SQL injection

How to create search box in php?

I have implemented search box for my website by using php, html and jquery.
Firstly, I have created a database,
using php I have sorted the values and
using jquery and html I have shown the search result in a div below the search box.
My problem is that I am not able to select the result using down or up key, for this I also tried to make the result in list or drop box in php.
Please correct me if I am wrong some where. Below is the code which is I am using.
<body>
<h1>Search web page</h1>
<form action="search_demo.php" method="post" >
<input type="text" name="search" placeholder="search here" onkeydown="searchq();" />
<input type="submit" value=">>" />
<div id="output" style="z-index: 10; position: absolute ; background-color: yellow;">
</div>
<div id="stable" style="">
</div>
</form>
</body>
<script>
function searchq(){
var searchtxt = $("input[name='search']").val();
$.post("search_demo12.php", {searchval : searchtxt}, function(output) {
$("#output").html(output);
});
}
</script>
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['searchval'])){
$search = $_POST['searchval'];
// $search = preg_replace("#[^0-9a-z]#i","",$search);
$pieces = explode(" ", $search);
$pieces_count = count($pieces);
// $pieces[0] = preg_replace("#[^0-9a-z]#i"," ",$pieces[0]);
// $pieces[1] = preg_replace("#[^0-9a-z]#i"," ",$pieces[1]);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select * from search_demo where fname like '%$search%' or lname like '%$search%'";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
}
echo ($output);
Do you mean you cannot select results using up and down keys?
I think it is because you are not wrapping options in select list . Do this
while($row = $result->fetch_assoc()){
$pname = $row['fname'];
$purl = $row['lname'];
//if($piece == $row['brand']){
$output .= '<option>'.$pname.' '.$purl.'</option>';
}
echo "<select>".$output."</select>";
In this case I think that it's better to use onkeyup() JavaScript function as you are implementing live search and need output to be changed dynamically..

php search function dynamically show results with javascript

I have the following php script which works fine, it uses the search term and compares it with a few different fields, then prints out the each record that matches:
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
while ($row = mysql_fetch_array($sql)){
echo '<br/> Name: '.$row['name'];
echo '<br/> Barcode: '.$row['barcode'];
echo '<br/> Serial: '.$row['serial'];
}
?>
And this is the form that links to it:
<form action="http://localhost/test/search.php" method="post">
Search: <input type="text" name="search" /><br />
<input type="submit" name="submit" value="Submit" />
</form>
I need to some how encode the results of the search so I can use them in a javascript function, then I can display them on the same html page below the form.
For that you have to use AJAX. You can send data back to the same page using JSON.
Advice - Don't use mysql_* functions since they are deprecated. Learn mysqli_* and try using that.
<script>
$(function(ev){
ev.preventDefault();
$("form").on('submit', function(){
var form = $(this);
var url = form.attr('action');
var data = form.serialize();
$.post(url, data)
.done(function(response){
if(response.success == TRUE)
{
// Search result found from json
// You have to loop through response.data to display it in your page
// Your single loop will have something like below -
var name = response.data.name;
var barcode = response.data.barcode;
var serial = response.data.serial;
$("#name").html(name);
$("#barcode").html(barcode);
$("#serial").html(serial);
}
else
{
// search result not found
}
});
});
});
</script>
On search.php
<?php
mysql_connect ("localhost", "root","") or die (mysql_error());
mysql_select_db ("table");
$search = isset($_POST['search']) ? $_POST['search'] : '';
$sql = mysql_query("select * from asset where
name like '%$search%' or
barcode like '%$search%' or
serial like '%$search%' ");
$num = mysql_rows_nums($sql);
$json = array();
if($num > 0)
{
$json['success'] = TRUE;
while ($row = mysql_fetch_array($sql)){
$json['data']['name'] = $row['name'];
$json['data']['barcode'] = $row['barcode'];
$json['data']['serial'] = $row['serial'];
}
}
else
{
$json['success'] = FALSE;
}
return json_encode($json);
?>

Categories