I am trying to create an autocomplete field using JQuery, which receives its autocompletions from a mysql database.
Index.php:
<!-- Place favicon.ico and apple-touch-icon.png in the root directory -->
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.0/themes/base/jquery-ui.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="js/vendor/modernizr-2.6.2.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.2.min.js"><\/script>')</script>
<script src="js/plugins.js"></script>
<script src="js/main.js"></script>
<script type="text/javascript">
$(function() {
$("#college").autocomplete({
source: "search.php",
minLength: 2
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
<fieldset>
<legend>jQuery UI Autocomplete Example - PHP Backend</legend>
<label for="state">State (abbreviation in separate field): </label>
<input type="text" id="college" name="college" />
<input type="submit" name="submitBtn" value="Submit" />
</fieldset>
</form>
<?php
if (isset($_POST['submit'])) {
echo "<p>";
while (list($key,$value) = each($_POST)){
echo "<strong>" . $key . "</strong> = ".$value."<br />";
}
echo "</p>";
}
?>
<!--[if lt IE 7]>
<p class="chromeframe">You are using an <strong>outdated</strong> browser. Please upgrade your browser or activate Google Chrome Frame to improve your experience.</p>
<![endif]-->
<!-- Add your site or application content here -->
<!-- Google Analytics: change UA-XXXXX-X to be your site's ID. -->
<script>
var _gaq=[['_setAccount','UA-XXXXX-X'],['_trackPageview']];
(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js';
s.parentNode.insertBefore(g,s)}(document,'script'));
</script>
</body>
</html>
search.php:
/* Connection vars here for example only. Consider a more secure method. */
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$dbname = 'college';
try {
$conn = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);
}
catch(PDOException $e) {
echo $e->getMessage();
}
$return_arr = array();
if ($conn)
{
$ac_term = "%".$_GET['term']."%";
$query = "SELECT * FROM college_list where name like :term";
$result = $conn->prepare($query);
$result->bindValue(":term",$ac_term);
$result->execute();
/* Retrieve and store in array the results of the query.*/
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['name'] = $row['name'];
array_push($return_arr,$row_array);
}
}
/* Free connection resources. */
//$conn = null;
/* Toss back results as json encoded array. */
echo json_encode($return_arr);
?>
It's currently retrieving correctly from the database, because it's getting the correct number of autocompletions. However, they're all blank. It appears to not actually be feeding "name" back into the field and I can't seem to figure out why. Any ideas?
Without seeing the autocomplete code you are using, I would say that you need a 1-dimensional array instead of a 2-dimensional one as you are generating now.
You could try changing:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
$row_array['name'] = $row['name'];
array_push($return_arr,$row_array);
}
To:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, $row['name']);
}
edit: check the api documentation, you need to build your array differently, something like:
while ($row = $result->fetch(PDO::FETCH_ASSOC)) {
array_push($return_arr, array('label' => $row['name'], 'value' => $row['name']));
}
Related
I am developing a simple jquery autocomplete using php. It works just fine for the most part... but when I do certain searches, it does not detect specific entries. For example, when I search for "Si" I get a list including "Simon", but when I search for "Jo" there is nothing.
Here are the two files I have:
index.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Search</title>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.1/themes/base/minified/jquery-ui.min.css" type="text/css" />
</head>
<body>
<form action='' method='post'>
<p><label>Name:</label><input type='text' name='Name' value='' class='auto'></p>
</form>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
$(function() {
//autocomplete
$(".auto").autocomplete({
source: "search.php",
minLength: 2
});
});
</script>
</body>
</html>
search.php
<?php
define('DB_SERVER', 'localhost');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'xxx');
define('DB_NAME', 'xxx');
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 Name FROM People 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();
}
/* Return results as json encoded array. */
echo json_encode($return_arr);
}
?>
Might this have something to do with an exception list? Or have I made an error with the code?
As a newbie I am in awe of the great help from this site!
I want to get information from a database, and I want to put it in selectbox as option.
I tried to do it but I could not not put it what is my mistake?(db can connect I just delete server name )
I am not sure how I can put db rows in selectbox as option.
therefore, I think my code has a problem.
p.php
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM test" ;
$result = mysqli_query($conn, $sql) or die("Query: ($sql) [problem]");
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_row($result)) {
display("<option value=$row[seat_id]>",$row[seatnumber]."\n");
}
display ("</select>", "\n");
} else {
echo "0 results";
}
mysqli_close($conn);
function display($tag , $value) {
echo $tag . $value ;
}
?>
p.html
<html>
<head>
<meta charset="utf-8">
<link href="" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
function transfer(){
var pix = document.getElementById('pix').value;
document.abc.test.value =pix;
}
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>
<script>
function ajaxWay() {
// syntax: $.post(URL,data,callback);
$.get("p.php", function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
</script>
<body>
<div id="a" style="text-align:center;">
<form name="abc" method="get" action="p.php">
<select id='pix' onchange='ajaxWay()'>
<input type="button" value="click" onclick="transfer();">
<input type="text" name="test" id="test">
</form>
</div>
</body>
</html>
If your main problem is that you are not able to embed options into your HTML, try something like this:
<html>
<head>
<meta charset="utf-8">
<link href="" rel="stylesheet" type="text/css" />
</head>
<script type="text/javascript">
function transfer(){
var pix = document.getElementById('pix').value;
document.abc.test.value =pix;
}
</script>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js">
</script>
<script>
function ajaxWay() {
// syntax: $.post(URL,data,callback);
$.get("prefinal.php", function(dataFromtheServer) {
$("#result").html(dataFromtheServer);
});
}
</script>
<body>
<div id="a" style="text-align:center;">
<form name="abc" method="get" action="p.php">
<?php
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "SELECT * FROM test" ;
$result = mysqli_query($conn, $sql) or die("Query: ($sql) [problem]");
?>
<select id='pix' onchange='ajaxWay()'>
<?php
$row = mysqli_fetch_assoc($result);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_row($result))
{
echo '<option value="' . $row[0] . ">' . $row[0] . '</option>';
}
}
mysqli_close($conn);
?>
</select>
<input type="button" value="click" onclick="transfer();">
<input type="text" name="test" id="test">
</form>
</div>
</body>
</html>
Note that in the above I am using your code from p.php to generate the actual content for the select options. The form should NOT submit to p.php, but to some other script that will process the form and perform the required actions. I would help more if I knew more about what you were trying to achieve!
I am developing an application that has a question bank through which i want to generate a question paper randomly. I am using PHP and HTML. I am using html as my front end and for back end PHP. I have developed the code but there is a problem with it, its generating 4 textarea 2 for one question and i am unable to debug it
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "rgpv";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT ques FROM bank WHERE sub='$_POST[sub]' ORDER BY RAND() LIMIT 2";
$result = $conn->query($sql);
$result = $conn->query($sql);
// output data of each row
while($row = $result->fetch_assoc()) {
?>
<!DOCTYPE html>
<html >
<head>
<meta charset="UTF-8">
<title>Login Form</title>
<!-- Calling CSS -->
<link rel="stylesheet" href="css/reset.css">
<link rel='stylesheet prefetch' href='http://fonts.googleapis.com/css?family=Roboto:400,100,300,500,700,900|RobotoDraft:400,100,300,500,700,900'>
<!--File for fonts-->
<link rel='stylesheet prefetch' href='css/bootstrap.css'>
<link rel='stylesheet prefetch' href='css/font-awesome.min.css'>
<link rel="stylesheet" href="css/style.css">
</head> <!-- end Head -->
<body background="images/journal.jpg">
<!-- Mixins-->
<!-- Form Title-->
<div class="pen-title">
<h1>University Institute of Technology- RGPV</h1><h2>Random Question Paper Generator Portal</h2>
</div>
<fieldset class="form-group">
<label for="exampleTextarea">Question 1</label>
<textarea class="form-control txt" id="name" rows="3" value="" disabled><?php echo $row["ques"]; ?></textarea>
</fieldset>
<fieldset class="form-group">
<label for="exampleTextarea">Question 2</label>
<textarea class="form-control txt" id="name" rows="3" value="" disabled><?php echo $row["ques"]; ?></textarea>
</fieldset>
</body>
</html>
<?php
}
?>
<?php
function get_question()
{
// Connect to your database storing your questions
$connection = new mysqli("hostname", "username", "password", "database");
if($connection->connect_errno)
{
die("Error connecting to database.");
}
// Load all your questions from your database into an array
$query = "SELECT * FROM questions";
$result = $connection->query($query);
$questions = $result->fetch_all();
// Randomly select a question from your array to output
$number = rand(0, count($questions) - 1);
return $questions[$number];
}
$question = get_question();
// Use var_dump() to view the raw output from your database
// You can now output your question and format it however you'd like
var_dump($question);
// You can call this function as many times as you'd like using a loop
for($i = 0; $i < 10; $i++)
{
$question = get_question();
// Output your question properly formatted here
}
?>
Use a function like this & pull data from your db :
when ever you call it like : UniqueRandomNumbersWithinRange(0,25,5)
You will get an array $quantity of jumbled numbers between $min to $max.
From the backend just pull questions in the array order.
How can I make the suggestion list work using typeahead.js and with
database as the source?
Before trying the database code, the fixed source code is working.
But when I tried the database code, the database code does not work.
If possible, please explain why my database code does not work.
Fixed source code:
<html>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="//raw.github.com/jharding/typeahead.js-bootstrap.css/master/typeahead.js-bootstrap.css" rel="stylesheet" media="screen">
<script src="//twitter.github.com/typeahead.js/releases/latest/typeahead.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#citiesInput').typeahead({
name: "suggestion typeahead",
local: ["italy", "malaysia", "new york", "USA", "England"]
});
});
</script>
<input type="text" class="q typeahead" dir="auto" id="citiesInput" onkeyup="typeahead(this.value)" />
</html>
Database code:
<html>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="//raw.github.com/jharding/typeahead.js-bootstrap.css/master/typeahead.js-bootstrap.css" rel="stylesheet" media="screen">
<script src="//twitter.github.com/typeahead.js/releases/latest/typeahead.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#citiesInput').typeahead({
name: "suggestion typeahead",
remote: "/suggestion.php?q=%QUERY"
});
});
</script>
<input type="text" class="q typeahead" dir="auto" id="citiesInput" onkeyup="typeahead(this.value)" />
</html>
suggestion.php:
<?php
include 'connect.php'; //connect with database
$query = $_GET["q"];
if($query != "")
{
$safequery = mysqli_real_escape_string($con,$query);
$stmt = "SELECT * FROM searchengine WHERE title LIKE '%" . $safequery . "%' OR keywords LIKE '%" . $safequery . "%' OR link LIKE '%" . $safequery . "%' LIMIT 4";
$result = mysqli_query($con,$stmt) or die(mysqli_error($con));
$number_of_result = mysqli_num_rows($result);
if ($number_of_result > 0) {
//results found here and display them
while ($row = mysqli_fetch_assoc($result)) { //show first 10 results
$title = $row["title"];
$link = $row["link"];
echo "<div id='sugg-search-result'>";
echo "<a href='$link' id='sugg-title'>" . $title . "</a>";
echo "</div>";
}
}
}
?>
I can see 2 things wrong.
1) You need to specify the remote url (the documentation says it is required) UPDATE Seems that you can just set remote to the url. But I do see that they use single-quotes, where you are using double-quotes. Don't know if that matters.
2) Your php class needs to return valid JSON. You are returning html.
Database
<html>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap.min.css" rel="stylesheet" media="screen">
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<link href="//raw.github.com/jharding/typeahead.js-bootstrap.css/master/typeahead.js-bootstrap.css" rel="stylesheet" media="screen">
<script src="//twitter.github.com/typeahead.js/releases/latest/typeahead.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#citiesInput').typeahead({
name: 'suggestion-typeahead',
remote: {
url: '/suggestion.php?q=%QUERY',
datatype: 'json'
}
});
});
</script>
<input type="text" class="q typeahead" dir="auto" id="citiesInput" onkeyup="typeahead(this.value)" />
</html>
Suggestion.php
<?php
include 'connect.php'; //connect with database
$query = $_GET["q"];
if($query != "")
{
$safequery = mysqli_real_escape_string($con,$query);
$stmt = "SELECT * FROM searchengine WHERE title LIKE '" . $safequery . "%' LIMIT 4";
$result = mysqli_query($con,$stmt) or die(mysqli_error($con));
$arr = array();
$number_of_result = mysqli_num_rows($result);
if ($number_of_result > 0) {
//results found here and display them
while ($row = mysqli_fetch_assoc($result)) { //show first 10 results
//add $title to an array which you will call json_encode(arr) on.
$arr[] = $row["title"];
}
}
}
$json = json_encode($arr);
print_r($json);
?>
NOTE
I see that your suggestions.php file was returning the title and it's link with the html. Typeahead is supposed to return a list of strings. Once the user selects one of the suggested words, then you should lookup the link for that word.
This might be very easy for some of you but very hard for me since first time doing it.
By looking at some examples on the web, I ended up with the code below for auto-suggestion example but the code doesn't work.
Thanks
HTML
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('#textbox_postcode').autocomplete(
{
source: 'search-db.php',
minLength: 3
});
});
</script>
</head>
<body>
<form action="search.php" method="post">
<input type="text" id="textbox_postcode" value="" /> <input type="submit" value="Search" />
</form>
</body>
</html>
PHP
$keyword = ltrim(strtolower(strip_tags($_GET['keyword'])));
if (! $keyword) return;
$host =
'localhost'; $user = 'root'; $pswd = ''; $dtbs = 'geomaps';
$host_conn = mysql_connect($host, $user, $pswd); $dtbs_conn =
mysql_select_db($dtbs);
$return = array();
$sql = "SELECT id, postcode FROM postcodes WHERE postcode LIKE
'$keyword%' ORDER BY postcode"; $run = mysql_query($sql);
if (#mysql_num_rows($run) == 0) return;
while ($records = mysql_fetch_array($run, MYSQL_ASSOC)) { $return[] =
$records; }
echo json_encode($return);
Try changing $_GET['keyword'] to $_GET['term']