JQuery Autocomplete from Database - javascript

I need to to do autocomplete suggestion for my website and the data should be retrieved from database. I want to use JQuery autocomplete. here is my code but it doesn't work!
This is my php file with the name of gethint.php:
<?php
require_once ('config.php');
$q=$_REQUEST["q"];
$sql="SELECT `fname` FROM `Property` WHERE fname LIKE '%$q%'";
$result = mysql_query($sql);
$json=array();
while($row = mysql_fetch_array($result)) {
$json[]=array(
'value'=> $row['fname'],
'label'=> $row['fname']
);
}
echo json_encode($json);
?>
and then this is my html file :
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.18/jquery-ui.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
<script type="text/javascript">
$(document).ready(function(){
$("#hint").autocomplete({
source:'gethint.php',
minLength:1
});
});
</script>
</head>
<body>
<form class="sansserif" action="view.php" method="post">
Name: <input type="text" id="hint" name="hint" >
<input type="submit" name="submit" value="View">
</form>
</html>
It took a lot of time but I couldn't find the problem. I was wondering if someone could help me.
Thanks.

<?php
require_once ('..\config.php');
$q=$_REQUEST["term"];
$sql="SELECT `fname` FROM `Property` WHERE fname LIKE '%$q%'";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
$json[]=array(
'value'=> $row['fname'],
'label'=> $row['fname']
);
}
echo json_encode($json);
?>
All I changed was the $_REQUEST["q"] to $_REQUEST["term"].

I did some changes, maybe you need to fix something but take a look to see if helps...
The php:
<?php
require_once ('config.php');
$q=$_REQUEST["q"];
$sql="SELECT `fname` FROM `Property` WHERE fname LIKE '%$q%'";
$result = mysql_query($sql);
$json=array();
while($row = mysql_fetch_array($result)) {
array_push($json, $row['fname']);
}
echo json_encode($json);
?>
The html+jquery:
<html>
<head>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" />
</head>
<body>
<form class="sansserif" action="view.php" method="post">
Name: <input type="text" id="hint" name="hint" />
<input type="submit" name="submit" value="View">
</form>
<script type="text/javascript">
$(function() {
$( "#hint" ).autocomplete({
source: function( request, response ) {
$.ajax({
url: "gethint.php",
dataType: "jsonp",
data: {
q: request.term
},
success: function( data ) {
response( data );
}
});
},
});
});
</script>
</body>
</html>

Your PHP script should be accepting a term parameter, not q.

Related

Cannot implement autocomplete from mysql

I am struggling to implement autocomplete on my page as no results are showing from the database.
Below is the code on the index.php page
<head> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<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>
$(function() {
$("#tags").autocomplete({
source: "autocomplete.php"
});
});
</script> </head> <body> <label for="tags">Select Student</label> <div><input id="tags" type="text" name="tags" /> </div></body>
The autocomplete.php file looks like this...
<?php include("session.php");
session_start();
$description_arr = array();
$stmt = "select case
When (login.name is null or login.name='') and (login.surname is null or login.surname='')
then login.username
Else login.name + ' ' + login.surname
End as user_profile
from my_students
inner join login
on stud_id = login.id
where my_students.id = '$login_id'";
$ses_stmt = mysqli_query($conn, $stmt);
while($row = mysqli_fetch_array($ses_stmt)){
array_push($description_arr,$row['user_profile']);}
echo json_encode($description_arr);
?>

PHP/jQuery Instant Search Not Working

I'm trying out a tutorial to learn how to do instant search with PHP/jQuery. I can't seem to find why this code won't work. This search was working before when I had the PHP in the same file as the index, but when I moved it to another file, it stopped working. I keep getting this console error message with each keystroke: ReferenceError: Can't find variable: $_POST. Any help would be deeply appreciated.
index.php file
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset-utf-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
function searchkey() {
var searchTxt = $("input[name='search']").val();
$_POST("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
<title>Search</title>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" placeholder="Search for members..." onkeyup="searchkey();">
<input type="submit" value="Search">
</form>
<div id="output"></div>
</body>
</html>
search.php file (same location as index.php)
<?php
$connection = mysqli_connect('localhost','root','root','LBD');
$output='';
if(isset($_POST['searchVal'])){
$searchkey= $_POST['searchVal'];
$searchkey=preg_replace("#[^0-9a-z]#i", "", $searchkey);
$query = mysqli_query($connection,"SELECT * FROM members WHERE ownerName LIKE '%$searchkey%' OR companyName LIKE '%$searchkey%'") or die("Could not search!");
$count = mysqli_num_rows($query);
if($count == 0){
$output="There was no search result!";
}
else{
while($row=mysqli_fetch_array($query)){
$oName=$row['ownerName'];
$cName=$row['companyName'];
$output .='<div>'.$oName.'<br/>'.$cName.'</div>';
}
}
}
echo ($output);
?>
Looks like you've used the PHP $_POST in your script..
Try to use:
$.POST
Try this
$.ajax({
url: "search.php",
type: 'POST',
data: {
searchVal: searchTxt
},
})
.done(function(output) {
$("#output").html(output);
});

How to catch an Isset, or POST information, with a form in JQuery?

So I am trying to do something simple. There is a form, it does a self post and I want to get that post information from JQuery and put it into a div.
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
JQuery here to catch button click and do a "PHP_self":
<script>
$(document).ready(function(){
$(".gettingpostbutton").click(function(){
$.post( "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>", function( data ) {
$("#add_post_information_html_here").append(data+" number from $_POST");
});/**/
});
});
</script>
</head>
<body>
<?php
// define variables and set to empty values
$number = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$number = test_input($_POST["number"]);
}
For SQL Injection:
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>
Basic Form:
<h2>PHP Form Validation Example</h2>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
put a number: <input type="text" number="number">
<br><br>
<input type="button" name="action" class="btn btn-success gettingpostbutton" value="Add Number" />
</form>
Put info to page either through PHP but prefer to do it through JQuery:
<?php
echo "<h2>Your Input:</h2>";
echo $number;
?>
<div id="add_post_information_html_here"></div>
</body>
</html>
Result:

div dissapear after including php

When I want to include my search in index.php, slider.php just disappears.
The file search.php is combination of php and javascript and slider.php is pure javascript.
This is my index.php:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/mhgallery.js"></script>
<script type="text/javascript" src="js/initgallery.js"></script>
<script type="text/javascript" src="js/search.js"></script>
</head>
<body>
<?php include 'includes/search_form.php';?>
<?php include 'includes/slider.php';?>
</body>
</html>
This is search.php:
<?php
include 'init.php';
$output="";
if (isset($_POST['search'])){
$searchq = $_POST['search'];
$searchq = preg_replace ("#[^0-9a-z]#i","",$searchq);
$query = mysql_query("SELECT * FROM `users` WHERE `username` LIKE '%$searchq%'") or die("error");
$count = mysql_num_rows($query);
if ($count == 0){
$output = 'No resault';
}else{
while($row = mysql_fetch_array($query)){
$username = $row['username'];
$output .= '<div>'.$username.'</div>';
}
}
}
?>
This is search_form.php:
<?php include 'php_script/search.php';?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="search.js" type="text/javascript"></script>
<div id="search_box">
<form action = "index.php" method="POST">
<input id="box" type="text" name="search" placehoalder="Search" onkeydown="searchq();"/>
<input id="srch" type="submit" value=">>"/>
</form>
<div id="output">
<?php echo ($output);?>
</div>
</div>
This is slider.php:
<div id="mhgallery">
<style type="text/css"> #mhgallery img { display:none; } </style>
<img src="slideshow_slike/batman.jpg" title="batman" />
<img src="slideshow_slike/hobbit.jpg" title="hobbit" />
<img src="slideshow_slike/interstellar.jpg" title="interstellar" />
<img src="slideshow_slike/sw7.jpg" title="sw7" />
</div>
This is initgallery.js:
$(document).ready(function(){$("#mhgallery").mhgallery({width:950,height:400,scaleMode:'scaleToFill',firstSlide:0,randomPlay:false,autoPlay:true,backgroundMode:'transparent',backgroundColor:'#333333',showShadow:true,showThumbShadow:true,showPause:false,showBorder:true,borderSize:6,borderColor:'#FFFFFF',showFullscreen:false,fullscreenBackgroundColor:'#333333',fullscreenThumbArrowStyle:'white',interval:3000,effectSpeed:500,showCaption:false,textCSS:'.title {font-size:12px;font-weight:bold;font-family:Arial;color:#ffffff;line-height:200%;} .alt {font-size:12px;font-family:Arial;color:#ffffff;}',captionPosition:'bottom',captionBarColor:'#333333',captionBarOpacity:0.8,captionBarPadding:8,captionAlign:'center',showNavArrows:true,autoHideNavArrows:true,arrowStyle:'white',showThumbs:false,thumbSize:40,thumbGap:8,thumbBottom:-60,thumbArrowStyle:'black',thumbOpacity:0.8,thumbBorderWidth:1,thumbBorderColor:'#FFFFFF',thumbBorderActiveColor:'#FFFFFF',effect:'fade,slideLeft,slideRight,slideTop,slideBottom',jsFolder:'js'});});
This is search.js:
function searchq(){
var searchTxt = $("input [name='search']").val();
$.post("search.php", {searchVal: searchTxt}, function (output){
$("#output").html(output);
});
}

How to pass php variable to my script code and use document.write to display it?

This is my html code.
<!DOCTYPE HTML>
<?php
$php_var = "Hello world from PHP";
?>
<html style="margin-top:-8px; margin-left:-8px;">
<head>
<meta charset="utf-8">
<title>Pure-Convert</title>
<script src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="calchome.css">
<script src="4func.js" type="text/javascript"></script>
<script src="converter.js" type="text/javascript"></script>
<script>
var js_var = <?php echo json_encode($php_var); ?>;
document.write(js_var);
</script>
</head>
<body >
<form action="cool.php" method="post">
<input name ="username" placeholder="Name">
<input name= "comment" placeholder="Make your mind heard..." />
<input type ="submit">
</form>
</body>
</html>
Basically what I want to happen is I want $php_var to be converted to javascript. This what I have attempted. Can someone help me accomplish this?
<script>
var js_var = <?php echo json_encode($php_var); ?>;
document.write(js_var);
</script>
Try
<script>
var js_var = "<?php echo $php_var; ?>";
document.write(js_var);
</script>
You don't need document.write(js_var);. What it does is writes that value to the DOM/HTML, possibly messing up everything (depends on the value).
<? php echo( '<script>var my_var=' . $my_value . ';</script>'); ?>
// In further js:
console.log( my_var );

Categories

Resources