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!
Related
Hello I have been building a shout box and i am so close - i just cant get the fetched data to refresh on input.
the fetched data refreshes on interval but when i press submit i have to wait for it to refresh by that interval i would like it to be instant on submit
sql
CREATE TABLE IF NOT EXISTS `shoutbox` (
`msgid` int(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`message` text DEFAULT NULL,
PRIMARY KEY (`msgid`)
) ENGINE=MyISAM;
index.php
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap 5 Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<p id="shoutbox"></p>
<form id='contactForm1' name='contactForm1' action='postshout.php' method='post'>
<div class="row">
<div class="col-md-12">
<input id="message" class="form-control shoutbox_msgbox" type='text' size='100%' name="message">
</div>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
var frm = $('#contactForm1');
frm.submit(function (e) {
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log('Submission was successful.');
console.log(data);
},
complete: function(){
$("#message").focus().val('');
},
error: function (data) {
console.log('An error occurred.');
console.log(data);
},
});
});
</script>
<script>
function updateShouts(){
// always refresh #shoutbox
$('#shoutbox').load('getshout.php');
}
setInterval( "updateShouts()", 15000 );
updateShouts();
</script>
</body>
</html>
getshout.php
<?php
$servername = "localhost";
$username = "dbusername";
$password = "dbpassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$sth = $conn->prepare("SELECT * FROM shoutbox ORDER BY `msgid` DESC");
$sth->execute();
/* Fetch all of the remaining rows in the result set */
$result = $sth->fetchAll();
foreach ($result as $row) {
echo "$row[message]<br>";
}
postshout.php
<?php
$servername = "localhost";
$username = "dbusername";
$password = "dbpassword";
try {
$conn = new PDO("mysql:host=$servername;dbname=dbname", $username, $password);
// set the PDO error mode to exception
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $e) {
echo "Connection failed: " . $e->getMessage();
}
$data = [
'message' => $_POST['message'],
];
$sql = "INSERT INTO shoutbox (message) VALUES (:message)";
$stmt= $conn->prepare($sql);
$stmt->execute($data);
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.
I am attempting a bit of ajax for the first time. I'm trying to write a live search where on every character entered a search of a MySQL database is run.
This is my code so far:
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<script type="text/javascript">
function getStates(value){
$.post(
"getstates.php",
{partialState:value},
function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="input" onkeyup="getStates(this.value)" /><br />
<div id="results"></div>
</body>
</html>
getStates.php
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;dbname=livesearch","root", "usbw");
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$partialState = $_POST['partialState'];
$query = $dbh->prepare("SELECT state_name FROM tbl_state WHERE state_name LIKE '%$partialSate%'");
$query->execute();
$result = $query->fetchAll();
foreach($result AS $state){
echo '<div>'.$state['state_name'].'</div>';
}
The mySQL database is constructed correctly using the correct table names etc.
Why is it not returning the resulting states from the database?
The problem is that you have made a typo in your query:
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE '%$partialSate%'");
^^^^Missing t
Should be
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE '%$partialState%'");
But you should also use prepared query's correctly:
Fixed code:
<?php
if(isset($_POST['partialState'])){
//test the connection
try{
//connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;dbname=livesearch","root", "usbw");
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbh->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE,PDO::FETCH_ASSOC);
//if there is an error catch it here
} catch( PDOException $e ) {
//display the error
echo $e->getMessage();
}
$query = $dbh->prepare("SELECT state_name
FROM tbl_state
WHERE state_name
LIKE :like");
$query->execute(array(':like'=>'%'.$_POST['partialState'].'%'));
$result = $query->fetchAll();
foreach($result AS $state){
echo '<div>'.$state['state_name'].'</div>';
}
die();
}
?>
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
function getStates(value){
$.post("index.php", { "partialState":value },
function(data){
$("#results").html(data);
});
}
</script>
</head>
<body>
<input type="text" name="input" onkeyup="getStates(this.value)" /><br />
<div id="results"></div>
</body>
</html>
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']));
}