I need to make a autocomplete input in materialize css page,
I've tried this code but did not work. Do you have any idea how to make this possible?
From here Autocomplete Textbox using jQuery, PHP and MySQL
index.php
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'search.php'
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="skills">Skills: </label>
<input id="skills" type="text">
</div>
search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'u969692298_dogs';
$dbPassword = 'dogs123';
$dbName = 'u969692298_dogs';
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$searchTerm = $_GET['term'];
$query = $db->query("SELECT * FROM kennels WHERE name LIKE '%".$searchTerm."%' ORDER BY name ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['name'];
}
echo json_encode($data);
?>
What about something like this:
The result from this snippet suggests country name when you start typing in input box with materialize css framework.
Example with API GET request
$(document).ready(function() {
//Autocomplete
$(function() {
$.ajax({
type: 'GET',
url: 'https://restcountries.eu/rest/v2/all?fields=name',
success: function(response) {
var countryArray = response;
var dataCountry = {};
for (var i = 0; i < countryArray.length; i++) {
//console.log(countryArray[i].name);
dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
}
$('input.autocomplete').autocomplete({
data: dataCountry,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<div class="input-field">
<input type="text" id="autocomplete-input" class="autocomplete" autocomplete="off" name="name">
<label for="autocomplete-input">Country Name</label>
</div>
</div>
</div>
Above code by Jaikhlang Brahma answer
Example with POST request
Jquery
$(document).ready(function() {
//Autocomplete
var inp_val = document.getElementById("myInput").value;
var dataString = "name="+inp_val;
$(function() {
$.ajax({
type: 'POST',
url: 'suggest-country.php',
data: dataString,
success: function(response) {
var countryArray = response;
var dataCountry = {};
for (var i = 0; i < countryArray.length; i++) {
//console.log(countryArray[i].name);
dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
}
$('input.autocomplete').autocomplete({
data: dataCountry,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
HTML
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<div class="input-field">
<input type="text" id="autocomplete-input" class="autocomplete" autocomplete="off" name="name">
<label for="autocomplete-input">Country Name</label>
</div>
</div>
</div>
PHP (suggest-country.php)
<?
header('Content-type: text/html; charset=UTF-8');
$dbHost = 'localhost';
$dbUsername = 'u969692298_dogs';
$dbPassword = 'dogs123';
$dbName = 'u969692298_dogs';
$conn = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$query = trim(str_replace(" ", " ", $_POST['name']));
$str = htmlspecialchars($query);
$q = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$sql = $conn->prepare("SELECT * FROM kennels WHERE name = ? ORDER BY name ASC");
$sql->bind_param("s", $q);
$sql->execute();
$rs = $sql->get_result();
$arr = array();
while($row = $rs->fetch_assoc()){
$arr["name"] .= $row["name"];
$arr["flag"] .= $row["flag"];
}
// echo "<pre>".json_encode($arr)."</pre>";
echo json_encode($arr);
?>
This PHP code is pretty secure and working nicely.
For more relevancy use MYSQL FULL TEXT SEARCH or replace this SQL query
$sql = $conn->prepare("SELECT * FROM kennels WHERE name = ? ORDER BY name ASC");
$sql->bind_param("s", $q);
$sql->execute();
To this
$sql = $conn->prepare("SELECT *, " . " MATCH(name) AGAINST(? IN BOOLEAN MODE) AS relevance " . " FROM kennels" . " ORDER BY relevance DESC LIMIT 8");
$sql->bind_param("s", $q);
$sql->execute();
$rs = $sql->get_result();
Hope this is helpful to you, I know how old this post is, but I want to help other newbies who are experiencing this problem.
Thank you 😊
Related
Previously I could not know about ajax. therefore I want to ask.
I want to display my wordlist from mysql into a text field but in array. this is the index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div class="container" >
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>
<script type="text/javascript">
$(document).ready(function() {
$("#display").click(function() {
$.ajax({
type: "GET",
url: "view_ajax.php",
dataType: "html",
success: function(){
$('').html();
}
});
});
});
</script>
And then this is the process.php
<?php
$host = "localhost";
$user = "root";
$password = "";
$dbname = "posts";
$con = mysqli_connect($host, $user, $password, $dbname);
if (!$con) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "select wordlist from word";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('wordlist'=>$row[0]));
}
echo json_encode(array('result'=>$result));
mysqli_close($con);
?>
I will be very helpful if you can give an answer. Thank you
Change your PHP loop to something like this:
$result = array();
while($row = mysqli_fetch_array($res)){
$result[]= $row[0];
}
echo json_encode(array('wordlist'=>$result));
Then, in your JS, see below
$(document).ready(function() {
$("#display").click(function() {
/*$.ajax({
type: "GET",
url: "view_ajax.php",
dataType: "json",
success: function(response){
// use the code below in this area
}
});*/
let response = {
"wordlist": ["This", "is", "the", "return", "from", "your", "server"]
} // this is what the response object will look like in your success function above
let output
// normal comma delimited response
output = response.wordlist.join(",");
// or if you want to keep the quotes
output = JSON.stringify(response.wordlist);
output = output.substr(1, output.length - 2);
// use .val() to set the value of an input
$('#wordlist').val(output);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container">
<h2>View data</h2>
<h4>Word List : </h4>
<div class="form-group">
<input id="wordlist" type="text" class="form-control" name="wordlist">
</div><br>
<button id="display" title="Generate Word">Generate</button>
<div class="input-single">
</div>
The values in the Autocomplete are first name and last name. I need to divide them into two strings, fn and ln, and send them to a PHP function to calculate the result.
I'm not sure how to separate the name into two values and send them to another PHP function which calculates the relation between these two people need their first name and last name to determine their id.
<html>
<?php include ('relation.php');?>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$("#fname").autocomplete({
source: 'mysql.php'
});
});
$(function() {
$("#fname2").autocomplete({
source: 'mysql.php'
});
});
</script>
<div class="ui-widget">
<label for="skills">fist person: </label>
<input id="fname">
</div>
<div class="ui-widget">
<label for="skills">second person </label>
<input id="fname2">
</div>
<div class="ui-widget">
<label for="skills">Skills: </label>
<button id="search" onclick="">
</div>
?>
</html>
<?php
//database configuration
$dbHost = 'localhost:3308';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'village';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM individual WHERE fname LIKE
'%".$searchTerm."%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['fname']." ".$row['lname'];
}
//return json data
echo json_encode($data);
?>
//relation.php
function calculate_relationship($a_id, $b_id)
function aggrandize_relationship($rel, $dist, $offset = 0) {
function lowest_common_ancestor($a_id, $b_id)
function lowest_common_ancestor($a_id, $b_id)
function get_ancestors($id, $dist = 0)
.....
function getid($fname,$lname){
$conn = OpenCon();
get matched data from skills table
$query = $conn->query("SELECT id FROM individual WHERE fname LIKE
'%".$fname."%' and lname LIKE '%".$lname."%'");
$row = $query->fetch_row();
return $row[0];8*/
}
if( $_GET['fn1'] && $_GET['ln1']&&$_GET['fn2'] && $_GET['ln2']) {
$relation=calculate_relationship(getid($_GET['fn1'],$_GET['ln1']),getid($_GET['f
n2'],$_GET['ln2']));
}
//$relation=calculate_relationship($_GET['fn1'],$_GET['fn2']);
if($relation!='')
echo " a is the " .$relation." of b ";
else
echo "There's no relation between a and b ";
I have the below two files.
How do I get AJAX to populate a label and a value
For example if value is Chicago, IL. How do I get the value to be only Chicago on Submitting the form?
Below the field populates as, for example, Chicago, IL
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-3-typeahead/4.0.2/bootstrap3-typeahead.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h2 align="center"></h2>
<br /><br />
<label>Search Country</label>
<input type="text" name="city" id="city" class="form-control input-lg" autocomplete="off" placeholder="Type City Name" />
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#city').typeahead({
source: function(query, result)
{
$.ajax({
url:"TypeaheadTest2.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
});
</script>
Below is file TypeaheadTest2.php
<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_assoc($result))
{
$data[] = $row['city'] . ' ' . $row['state'];
}
echo json_encode($data);
}
?>
If I am getting you right, you are so close to what you are expecting.
I see that you are concatenating the city and state name on the server side. But you want to display only city name on typeahead options.
I would suggest you pass on the city name and state name as separate attributes of an object from PHP and then use them as you want on Javascript side.
Here is the sample code,
PHP:
<?php
$connect = mysqli_connect("localhost", "", "", "");
$request = mysqli_real_escape_string($connect, $_POST["query"]);
$query = "
SELECT * FROM state WHERE state LIKE '".$request."%' OR city LIKE '%".$request."%'
";
$result = mysqli_query($connect, $query);
$data = array();
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_assoc($result)){
$data[] = array('city'=>$row['city'], 'state'=>$row['state']);
}
echo json_encode($data);
}
?>
Javascript:
$(document).ready(function(){
$('#city').typeahead({
source: function(query, result) {
$.ajax({
url:"TypeaheadTest2.php",
method:"POST",
data:{query:query},
dataType:"json",
success:function(data) {
result($.map(data, function(item){
return item.city;
}));
}
});
}
});
});
I am trying mas a simple HTTP post request using AXIOS.Its like an Ajax request to retrieve the data . Here is the HTML. Its sends a post request to the getData.php.
<!doctype html>
<html>
<head>
<title>axios - post example</title>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"/>
</head>
<body class="container">
<h1>Axios.post</h1>
<form role="form" class="form" onsubmit="return false;">
<div class="form-group">
<label for="data">Output</label>
<textarea id="data" class="form-control container" rows="5"></textarea>
</div>
<button id="post" type="button" class="btn btn-primary">POST</button>
</form>
<!--<div id="output" class=""></div>-->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<script>
(function () {
document.getElementById('post').onclick = function () {
var output = document.getElementById('data');
axios.post('getData.php')
.then(function (res) {
// console.log(res.data);
output.className = 'container';
for (i = 0; i < res.data.length; i++) {
output.innerHTML = res.data[i].id + "\n" + res.data[i].name;
}
})
.catch(function (err) {
output.className = 'container text-danger';
output.innerHTML = err.message;
});
};
})();
</script>
</body>
</html>`
In the getData.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
// Create connection
$conn = mysqli_connect($servername, $username, $password,"db_test");
$sql = "SELECT * FROM user";
$result = $conn->query($sql);
$resultArray = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$resultArray[] = $row;
}
echo json_encode($resultArray);
return;
} else {
echo "0 results";
}
$conn->close();
?>
But when i am trying to for loop through the array it returns only the last row.It fetches the data from the table and create an array. Whats wrong with the for loop ?
output.innerHTML = res.data[i].id + "\n" + res.data[i].name;
will just replace everything previously added.
output.innerHTML += res.data[i].id + "\n" + res.data[i].name;
would fix your problem.
Because your overwriting output.innerHTML In for loop so last value only exists .
use appendChild()
output.appendChild(res.data[i].id + "\n" + res.data[i].name);
Here i have simple search engine to search usernames. when people type username i want them to see results below search box and have them taken to search page only after they hit enter (like facebooks search engine).
html
<div class="search">
<form action="search.php" method="GET">
<input type="text" name="Search" size="50">
<input type="submit" value="Search">
</form>
</div>
php (search.php)
<?php
require 'includes/connection.php';
$term = $_GET['Search'];
$query_ver = "select * from Members where Name like '%$term%'";
$query = mysqli_query($dbc, $query_ver);
while($row = mysqli_fetch_array($query)) {
$name = $row['Name'];
}
echo $name;
?>
so is there a way to display $name below search box only with php and html
HTML
<div class="search">
<form action="search.php" method="GET">
<input type="text" name="search" size="50" class="search">
<input type="submit" value="Search">
</form>
</div>
Javascript
<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: "result.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();
}
});
$(\'#searchid\').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
search.php
<?php
include('db.php');
if($_POST)
{
$q = mysql_real_escape_string($_POST['search']);
$strSQL_Result = mysql_query("select id,name,email from live_search where name like '%$q%' or email like '%$q%' order by id LIMIT 5");
while($row=mysql_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">
<img src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/27301_312848892150607_553904419_n.jpg" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span> <br/><?php echo $final_email; ?><br/>
</div>
<?php
}
}
?>
for reference here is good solution
LINK1
LINK2