multiple values suggestion in textbox with jquery autocomplete - php

Could someone kindly help me adding some modifications to my php code so that it allows users to get more than one auto-suggestion? (Now it works fine for one value, but I would like that he/she receives auto suggest for more values, (for example after inserting a comma, again auto-complete suggestions will be shown ).
This is the HTML code:
<p><label>Actor/actress:</label><input type='text' name='name' value='' class='auto'></p>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
//autocomplete
$(".auto").autocomplete({
source: "actorsauto.php",
minLength: 2
});
});
</script>
and this is php code:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', 'xxxxxx');
define('DB_NAME', 'imdb');
if (isset($_GET['term'])){
$return_arr = array();
try {
$conn=new PDO('mysql:dbname=imdb;host=localhost', 'root', 'xxxxx');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT name FROM name WHERE name LIKE :term');
$stmt->execute(array('term' => '%'.$_GET['term'].'%'));
while($row = $stmt->fetch()) {
$return_arr[] = $row['name'];
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
}
?>
I am newbie in jquery and php and appreciate all your ideas.

You can put together a where statement by spliting the search term, for example at every space the user typed. Let's say he searched for music cd. The following code would get everything that has the string cd or music in it.
$stmt = $conn->prepare('SELECT name FROM name WHERE :where');
if($_GET['term']){
$termParts = explode(' ', $_GET['term']);
$whereParts = array()
foreach($termParts as $term){
$whereParts[] "name LIKE '%".$term."%'";
}
$where = implode(' OR ', $whereParts);
} else {
$where = 1;
}
$stmt->execute(array('where' => $where));

Related

dynamic drop-down not working

I am trying to implement a dynamic drop-down list using Ajax and PHP. Based on the index value in the first option list, second one should give me list of names with that id.
select1.php :
<html>
<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch1.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
</script>
</head>
<body>
<p id="heading">Dynamic Select Option Menu Using Ajax and PHP</p>
<center>
<div id="select_box">
<select onchange="fetch_select(this.value);">
<option>Select ID</option>
<?php
$host = 'localhost';
$user = 'admin';
$pass = 'admin';
$dbname='kancha';
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "select distinct id from test";
$select= $conn->query($sql);
if ($select->num_rows > 0) {
while($row = $select->fetch_assoc()) {
echo "<option value='".$row['id']."'>".$row['id']."</option>";
//echo "<option value=>".$row['id']."</option>";
}
} else {
echo "0 results";
}
?>
</select>
<select id="new_select">
</select>
</div>
</center>
</body>
</html>
fetch1.php
<?php
if(isset($_POST['get_option']))
{
$host = 'localhost';
$user = 'admin';
$pass = 'admin';
$dbname='kancha';
$conn = new mysqli($host, $user, $pass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$id = $_POST['get_option'];
//echo '$id';
$sql = "select id, name from test where id='$id'";;
$find= $conn->query($sql);
if ($find->num_rows > 0) {
while($row = $find->fetch_assoc()) {
//echo "<option>".$row['name']."</option>";
echo "<option value='".$row['id']."'>".$row['name']."</option>";
}
} else {
echo "0 results";
}
exit;
}
?>
My database looks something like this :
SELECT * from test;
id name
1 Name1
2 Name2
1 Name3
The first drop down works just fine. However the second drop down isn't working.
I have attached the screenshot of it as well. Is there a problem in sending data across the files or what? Not able to figure out where has the code gone wrong.
For the second option list, when I have selected 1, I should be getting Name1 and Name3 as options but I get none.
EDIT: Corrected javascript in select1.php
You are setting the content for new_select with the wrong variable.
It should be response rather than val
Change to:
document.getElementById("new_select").innerHTML=response;
And assign value to your return options.
Like:
echo "<option value='".$row['id']."'>".$row['name']."</option>";
And change your sql string to the following for the above to work.
$sql = "select id, name from test where id='$id'";
And make sure your jquery.js include is being loaded.
Add value to the Option in selectbox, right now there is no value passing from the fetch_select()

autocomplete with MySQLi and php(via Autocomplete UI)

I am trying to make an autocomplete php interacts with database, but find more than 10 online resource, cannot make it work with my database.
Here is the index.php code:
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.10.1/jquery-ui.min.js"></script>
<script>
$(function() {
//autocomplete
$("#model").autocomplete({
source: "search.php",
minLength: 1
});
});
</script>
</head>
<body>
<form action='' method='post'>
<p><label>Model:</label><input type='text' id="model" name='model' class='model'/></p>
</body>
</html>
Here is the search.php:
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'root');
define('DB_PASSWORD', '123456');
define('DB_NAME', 'inventory');
if (isset($_GET['term'])){
$return_arr = array();
$conn = new mysqli(DB_SERVER,DB_USER,DB_PASSWORD,DB_NAME);
$stmt = $conn->stmt_init();
$term = '%'.$_GET['term'].'%';
$stmt = $conn->prepare("SELECT name from items WHERE name like ?");
$stmt->bind_param("s", $term);
$stmt->execute();
$stmt->bind_result($models);
while( $row = $models){
$return_arr[] = $row['name'];
}
echo json_encode($return_arr);
}
?>
And some tutorial use fetch_array() that is not working on my script why? It only work with regular loop such as while loop to store array from database and then use foreach to echo every rows. I am using $mysqli->fetch_array().
Which part is wrong?
You should do this:
Replace the "bind_result" line with this (just for convenience):
$stmt->bind_result($name);
Then replace your while loop with this:
while ($stmt->fetch()) {
$return_arr[] = $name;
}
And it should work.
Basically for each column in your query you add a variable in the bind_result statement and use those when iterating over the results;
use below codes and go through the url#,
http://www.codexworld.com/autocomplete-textbox-using-jquery-php-mysql/
//get matched data from skills table
$query = $db->query("SELECT * FROM skills WHERE skill LIKE '%".$searchTerm."%' ORDER BY skill ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['skill'];
}
//return json data
echo json_encode($data);

Livesearch php and ajax

I'm having some troubles with my code, I want it to execute the php file whenever I enter something but it isn't working
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
function getStates(value) {
$.post("search.php", {name:value},function(data)
$("#results").html(data);
});
}
</script>
</head>
<input type="text" onkeyup="getStates(this.value)"/>
<br>
<div id="results"></div>
<body>
</body>
</html>
php
<?php
mysqli_connect("localhost", "#", "#") or die(mysqli_connect_errno());
mysql_select_db("#") or die(mysql_error());
$search = $_POST["name"];
$players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
while($player = mysql_fetch_array($players)) {
echo "<div>" . $players["firstname"] . "</div>";
}
?>
From what I can see,you should change this
'%search%'
to
'%{$search}%'
in
$players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
EDIT
#user3187651 Assuming you've done everything right on the server side.
Change your javascript to:
function getStates(value) {
$.post("search.php", {name:value},function(data){
$("#results").html(data);
}
);
}
This should get rid of the error in the client side.
You are missing {. Just do:
function xyx(name) {
$.post("search.php", { name: value }, function(data) {
$("#results").html(data);
});
}
There's something that is missing in your code:
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> //ur getting the jquery via online
<script>
$(document).ready(function(){
$("#textBoxId").change(function() //triggers when you change the value in your textbox
{
var value = $(this).val(); //gets the value of your textbox
$.post("search.php", {id:value},function(data)
$("#results").append(data);
});
}
});
</script>
</head>
<body>
<input type="text" id="textBoxId"/>
<br>
<div id="results"></div>
</body>
</html>
And in your php:
<?php
mysqli_connect("localhost", "#", "#") or die(mysqli_connect_errno());
mysql_select_db("#") or die(mysql_error());
$search = $_POST['id'];
$returnData = "";
$players = mysql_query("SELECT firstname FROM players WHERE firstname LIKE '%search%'");
while($player = mysql_fetch_array($players)) {
$returnData .= "<div>" . $players["firstname"] . "</div>";
}
echo $returnData;
For more secure and creative back-end code, you can use this.
<?php
$host = 'localhost';
$user = 'root';
$password = '';
$database = 'dev_testing';
$mysqli = new mysqli($host, $user, $password, $database);
$username = $_GET['username'];
$username = trim(htmlspecialchars($username));
$like = '%' . strtolower($username) . '%';
$statement = $mysqli -> prepare('
SELECT name, picture, description
FROM users
WHERE lower(name) LIKE ?
ORDER BY INSTR(title, ?), title
LIMIT 20'
);
if (
$statement &&
$statement -> bind_param('ss', $like, $username) &&
$statement -> execute() &&
$statement -> store_result() &&
$statement -> bind_result($name, $picture, $description)
) {
$array = [];
while ($statement -> fetch()) {
$array[] = [
'name' => $name,
'picture' => $picture,
'description' => $description
];
}
echo json_encode($array);
exit();
}
Advantages of the code
Prevents SQL Injection
Orders results from the best match
Sends a JSON response (JSON is light-weight)
Full Tutorial:
Live Search with AJAX, PHP, and MYSQL

split output value via ajax,

Inside my page I have an input ("Model") with a datalist attribute and a select menu ("Brand"). When a user select one of the options of the datalist from the Model, it will dynamically change the options value from the Brand select menu. Both options value from Model and Brand are called from the database. This is what I code so far;
<input type="text" name="type" id="type" list="datalist1" onchange="fw();"/>
<datalist id="datalist1">
<?php
$query9 = "SELECT DISTINCT model FROM server ORDER BY model ASC";
$result9 = mysql_query($query9);
while($row9 = mysql_fetch_assoc($result9))
{
echo '<option value="'.$row9['model'].'">';
} ?>
</datalist>
<select name="brand" id="test2"><option value="">-- Select Brand--</option></select>
Script;
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function fw()
{
var selname = $("#type").val();
$.ajax({ url: "getBrand.php",
data: {"brand":brand},
type: 'post',
success: function(output) {
document.getElementById('test2').options.length = 0;
document.getElementById('test2').options[0]=new Option(output,output);
// document.getElementById('test2').options[1]=new Option(output,output);
}
});
}
</script>
getBrand.php
<?php
define('DB_HOST1', 'localhost');
define('DB_NAME1', 'standby');
define('DB_USER1', 'root');
define('DB_PASS1', '');
$link = mysql_connect(DB_HOST1, DB_USER1, DB_PASS1);
if(!$link)
{
exit('Cannot connect to server "' . DB_HOST1 . '"');
}
mysql_select_db(DB_NAME1, $link) or die('Cannot use database "' . DB_NAME1 . '"');
if (isset($_POST['brand'])) {
$selname = $_POST['brand'];
$query = "SELECT * FROM server WHERE model='$brand'";
$res = mysql_query($query);
$aBrand= array();
while($rows = mysql_fetch_assoc($res)) {
$brand= $rows['brand'];
$aBrand[] = $brand;
echo $aBrand[0];
echo $aBrand[1];
}
} ?>
From what I have coded, I have succesfully change the select menu dynamically but there is one problem. When there is more one data is called from getBrand.php, the 'output' in the select menu will combine all of the data into one line. For example, if the data is "M3000" and "M4000", it will display as "M3000M4000". Now, how do I split it and make it as a normal select options?
I'm still learning Javascript and I hope anyone here can guide me.
NOTE : The code only works in Firefox because of the datalist attribute
Send your data from getBrand.php as
echo implode(";", $aBrand);
this will generate a string like M3000;M4000;M5000;M6000
and in your java script code break the string into array using this code.
StrArr = Str.split (";");
here 'Str' is your output given by getBrand.php, and 'StrArr' is the array which contains your brands.
add a special character in the string returned form php
PHP
elementcount=0;
while($row9 = mysql_fetch_assoc($result9))
{
if(elementcount>0)
echo '$<option value="'.$row9['model'].'">';//place a $ sign in start or you can for any special character
else
echo '<option value="'.$row9['model'].'">';
}
now in javascript
success: function(output) {
output = output.split("$");
document.getElementById('test2').options.length = 0;
//here now loop through the elements and add
for(var i=0,i<output.length-1)
document.getElementById('test2').options[0]=new Option(output[i],output[i]);
// document.getElementById('test2').options[1]=new Option(output,output);
}

Can't transfer JSON string from PHP file to a getJSON method in Jquery

This is what I want, on a PHP page called input.php the user submits a username by a html form. This gets stored into the MYSQL database. There is a page called results.php which querys the MYSQL database for all usernames.
What I need to happen is that every 5 or so seconds some jquery code (maybe getJSON) will get a JSON string from results.php (the same page). This JSON string may be updated as a user may of added more usernames on the input.php page.
This is the input.php file
<form name="input" action="<?php $_SERVER['PHP_SELF']?>" method="post">
Usernames: <input type="text" name="usernames" />
<input type="submit" value="Submit" name="submit" />
</form>
<?php
if(isset($_POST['submit'])) {
$link = mysql_connect('', '', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('', $link);
if (!$db_selected) {
die ('Can\'t use : ' . mysql_error());
}
$result = mysql_query("INSERT INTO users(user_name) VALUES('".$_POST['usernames']."')");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
}
?>
This is the results.php file
<script
type="text/javascript" src="jquery-1.7.1.min.js"></script>
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('test', $link);
if (!$db_selected) {
die ('Can\'t use test : ' . mysql_error());
}
$result = mysql_query("SELECT user_name FROM users");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$names = array();
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $val) {
$names[][$key] = $val;
}
}
echo json_encode($names);
?>
<script type="text/javascript">
$.getJSON("http://localhost/test/results.php", function(json){
alert("JSON Data: " + json);
});
</script>
<div></div>
I am stuck on what jquery to put or even if i'm doing this properly. The end result is like Gmail where you receive email without a page refresh. But my system would retrieve usernames from the database every 5 seconds without a page refresh. I have read about getJSON method and I am totally out of my depth with it so I may need some very in depth explanation. If im going about this objective the wrong way please let me know and inform me of good practises in how to go about this.
I try this url in my browser with no result apart from the echoed JSON string from the php code.
this is my JSON string
[{"user_name":"matt"},{"user_name":"matt"},{"user_name":"peter"},{"user_name":"jim"},{"user_name":"sam"}]
what you are looking for is called AJAX, you will need javascript in order to acomplish it. if you want a sleek and easy way I would recommend jQuery.Your code would look something like this:
setTimeout(function(){
$.post("results.php",function(result){
//Do somthing with the result Array or object
},"json");
},5000);
moreover since you only are taking 1 piece of data "usernames" you should return an array json not an object json
["matt","matt","peter","jim","sam"]
it should take less bandwith for both, you and your user.
NOTE: you should remove the jquery script from results.php, the only thing you should retun is the json itself. if any doubt just ask
If you want to use results.php to do both things (i.e. display the usernames as well as respond to the JSON query) then you will need to split the file into two branches. Use a _GET variable to specify which branch. So for example, you would run .getJSON on results.php?json=true instead of just results.php. Now inside results.php have an if branch that checks for the existence of this _GET variable, and if so, grab the data you need, echo it in a json-encoded string, and then exit(). Do all this before anything else in results.php, even before the <script> tag .
Edited to provide code: (edited from OP's question)
<?php
$link = mysql_connect('localhost', 'root', '');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
$db_selected = mysql_select_db('test', $link);
if (!$db_selected) {
die ('Can\'t use test : ' . mysql_error());
}
$result = mysql_query("SELECT user_name FROM users");
if (!$result) {
die('Invalid query: ' . mysql_error());
}
$names = array();
while ($row = mysql_fetch_assoc($result)) {
foreach ($row as $key => $val) {
$names[][$key] = $val;
}
}
if (isset($_GET['json'])) {
echo json_encode($names);
exit();
}
?>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script type="text/javascript">
$.getJSON("http://localhost/test/results.php?json=true", function(json){
alert("JSON Data: " + json);
});
</script>
<div></div>
you can use setTimeout.
setTimeout( function() {
getData()
}, 5000);
function getData() {
$.getJSON("http://localhost/test/results.php", function(json){
alert("JSON Data: " + json);
});
});
}

Categories