How to view live search results in a selectable list? - php

I am totally new in jQuery so hope my question be simple:
I wrote a simple jQuery live search program with PHP and mySQL and it works good.
My question is: I want to show search results in a list then select one of the showing results to be written in the text box.
HTML code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(function (){
$(document).on('keyup', '[name="state"]', function() {
var partialState = $(this).val();
$.post("getStates.php",{partialState:partialState}, function(data){
$("#results").html(data);
});
});
});
</script>
</head>
<body>
<input type = "text" name = "state" autocomplete = "off"/>
<br>
<div id = "results"> </div>
</body>
</html>
My php code:
<?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
$con = mysqli_connect("localhost", "root", "")
or die("Failed to connect to the server: " . mysql_error());
mysqli_select_db($con, "airlines")
or die("Failed to connect to the database: " . mysql_error());
$partialStates = strtoupper($_POST['partialState']);
if(!$partialStates)
{
echo "";
}
else
{
$states = mysqli_query($con,"select distinct source from flights where source like '%$partialStates%'") or die(mysql_error());
while($row = mysqli_fetch_array($states))
{
echo "<div>" . $row['source'] . "</div>";
}
}
?>
Any help?

First look into prepared statement to prevent sql injection at where source like '%$partialStates%'.
Then, instead of returning HTML,
while($row = mysqli_fetch_array($states))
{
echo "<div>" . $row['source'] . "</div>";
}
it would be more convenient to work with JSON:
$sources = array();
while($row = mysqli_fetch_array($states)) {
$sources[] = $row['source'];
}
header('Content-Type: application/json');
echo json_encode($sources);
To select the first returned state, and update the input box. change
$.post("getStates.php",{partialState:partialState}, function(data){
$("#results").html(data);
});
to
$.getJSON( "getStates.php", { partialState: partialState }, function( states ) {
$('input').val(states[0]);
});

<?php
//PHP Code
error_reporting(E_ALL);
ini_set('display_errors', 1);
$con = mysqli_connect("localhost", "root", "root")
or die("Failed to connect to the server: " . mysql_error());
mysqli_select_db($con, "dedecms")
or die("Failed to connect to the database: " . mysql_error());
$partialStates = strtoupper($_GET['partialState']);
if(!$partialStates)
{
echo "###";
}
else
{
$states = mysqli_query($con,"select typename from dede_arctype where typename like '%$partialStates%'") or die(mysql_error());
$sources = array();
while($row = mysqli_fetch_array($states)) {
$sources[] = $row['typename'];
}
header('Content-Type: application/json');
echo json_encode($sources);
}
?>
HTML Code:
<html>
<meta charset="utf-8">
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function()
{
$(document).on('mouseout', '[name="state"]', function(){
var html;
var partialState = $(this).val();
$.getJSON("getStates.php",
{
partialState: partialState
}, function(states)
{
$('input').val(states[0]);
$.each(states, function(i, value)
{
html += value;
$("#results").html(html);
});
});
});
});
</script>
</head>
<body>
<input type="text" name="state" autocomplete="off" />
<br>
<div id="results"> </div>
</body>

Related

Is there any way in PHP to store $variable of $variable in session

I created a web-page,where you can search plant's scientific name. Type plant name in search_text it will give you results in search_result(live search like google and facebook search bar) . Ex: when you will type C in search input, in search result you will get C related search. Like C typed in search input, in search result it will start showing Cucumber(Cucumis sativus), Capsicum(Capsicum annuum), etc.
Now I want when you will click on Cucumber(Cucumis sativus) in search result, it have to direct to home.php/Cucumber . Or when user click on Capsicum(Capsicum annuum), it have to direct on home.php/Capsicum .
And on home.php in body tag I want to display plant name with their scientific name. And in para tag information related to plant search result.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Search</title>
<style type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </style>
<style type="text/javascript">
function searchq() {
var searchTxt = $("input[name='search']").val();
$.get("search.php", {searchVal: searchTxt}, function(output) {
$("#output").html(output);
});
}
</script>
</head>
<body>
<form action="index.php" method="post">
<input type="text" name="search" id="myInput1" autocomplete="off"
placeholder="Search username..." onkeydown="searchq(); " />
<input type="submit" value=">>"/>
</form>
<br>
<div id="output"></div>
</body>
</html>
search.php
<?php
$con = mysqli_connect('localhost', 'root');
mysqli_select_db($con, 'plant');
$output = '';
if (isset($_GET['searchVal'])) {
$searchq = $_GET['searchVal'];
$sql = "select * from type where plant like '%$searchq%'";
$query = mysqli_query($con, $sql) or die("could not search");
$count = mysqli_num_rows($query);
if ($count == 0) {
$output = 'There is no serach result';
} else {
while ($row = mysqli_fetch_array($query)) {
$plantname = $row['plant'];
$sciencename = $row['species'];
$id = $row['id'];
$output .= '<div>' . $plantname . ' ' . $sciencename . '</div>';
}
}
}
echo '<a herf="home.php/">' . $output . '</a></div>';
?>
There are many ways of doing this
Passing the name of the plant as a GET param is not an option?
You could do
echo "<a href='home.php?plantname={$plantname}' target='_blank'>{$output}</a></div>";
As the response of your server, that would create the link and in home.php you retrieve the plant name with $_GET['plantname'].
in home.php you do
if(isset($_GET['plantname'])){
echo $_GET['plantname'];
}
Please correct this line in index.php
<style type="text/javascript">
with
<script type="text/javascript">

AJAX: How do I get the label and value of a field to be different?

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;
}));
}
});
}
});
});

JSON for loop through array shows only last value

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);

How to make auto_search using ajax jquery, php and mysql

I have created auto suggest using Javascript AJAX now I want to create auto suggest using Jquery AJAX here is the code I have written using jquery AJAX
This is my indexa.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#search_input").keyup(function(){
var txt = $("#search_input").val();
$.get("search.inc.php?search_username="+document.search_form.txt, {suggest: txt}, function(result){
$("searchResults").html(result);
});
});
});
</script>
</head>
<body>
<form id="search" name="search_form" action="<?php $_SERVER['PHP_SELF']; ?> " method="post">
Search For Names : <input type="text" id="search_input" name="search_text"><br/><br/>
<!-- <input type="submit" > -->
</form>
<div id="searchResults"></div>
</body>
</html>
and this is my search.inc.php
<?php
if (isset($_GET['searched_username'])) {
$username = $_GET['searched_username'];
}
if (!empty($username)) {
if (#$db_connect=mysqli_connect('localhost', 'root', '')) {
if (#mysqli_select_db($db_connect,'my_databse')) {
$query_like = "SELECT `user_name` FROM `members_data` WHERE `user_name` LIKE '%". mysqli_real_escape_string($db_connect,$username)."%'";
$query_like_run = mysqli_query($db_connect,$query_like);
$query_num_rows = mysqli_num_rows($query_like_run);
if ($query_num_rows == NULL) {
echo 'No Result Found';
} else {
if ($query_num_rows == 1) {
echo $query_num_rows ." Result found<br/><br/>";
} else {
echo $query_num_rows ." Results found<br/><br/>";
}
foreach ($query_like_run as $searched_members) {
$searched_results = ''.$searched_members['user_name']."<br/>";
echo $searched_results;
}
}
}
}
}
?>
what I am doing worng . Please Help me
Remove the values from the url and change the key to search_username
Do the following:
<script type="text/javascript">
$(document).ready(function(){
$("#search_input").keyup(function(){
var txt = $(this).val();
$.get("search.inc.php", {searched_username: txt}, function(result){
$("#searchResults").html(result);//don't forget the # for the id
});
});
});
</script>
The param name is different between your indexa.php and search.inc.php files.
You should use
if (isset($_GET['search_username'])) { $username = $_GET['search_username']; }
or
if (isset($_GET['suggest'])) { $username = $_GET['suggest']; }
To get the value your wanted in search.inc.php file
or change search.inc.php?search_username="+document.search_form.txt
to
search.inc.php?searched_username="+document.search_form.txt

validation for existing data in both upper and lower case in using php

I am working on a form which has two fields. One is code and the other is name. I have a validation of checking the existing code in a database. The query for code seems to work fine but the same does not work for name, especially in lower case. Can anyone help me?
Here is my code:
<?php
session_start();
if (!isset($_SESSION["username"])) {
header("Location: unauthorize_access.php");
}
require("includes/dbconnect.php");
if (isset($_POST['save'])) {
$code = $_POST["code"];
$name = $_POST["name"];
{
mysql_query("INSERT INTO `country`(code, `name`)
Values
('$code', '$name')") or die(mysql_error());
print '<script type="text/javascript">';
print 'alert("RECORDS ADDED SUCCESSFULLY")';
header('refresh: 1; country.php');
PRINT '</script>';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Country</title>
<link rel="stylesheet" type="text/css" href="form2/view.css" media="all">
<script type="text/javascript" src="form2/view.js"></script>
<script type="text/javascript" src="form2/calendar.js"></script>
<script type="text/javascript">
function checkForm()
{
if(country.code.value == "") {
alert("Error: Code cannot be Empty!");
country.code.focus();
return false;
}
if(country.name.value == "") {
alert("Error: Name cannot be Empty!");
country.name.focus();
return false;
}
}
</script>
<script type="text/javascript" src="chk/jquery-1.2.6.min.js"></script>
<SCRIPT type="text/javascript">
<!--
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#code").change(function() {
var code = $("#code").val();
if(code.length >= 2)
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check_con.php",
data: "code="+ code,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#code").removeClass('object_error'); // if necessary
$("#code").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#code").removeClass('object_ok'); // if necessary
$("#code").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The code should have at least <strong>2</strong> characters.</font>');
$("#code").removeClass('object_ok'); // if necessary
$("#code").addClass("object_error");
}
});
});
//-->
</SCRIPT>
<SCRIPT type="text/javascript">
<!--
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#code").change(function() {
var code = $("#code").val();
if(code.length >= 2)
{
$("#status").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check_con.php",
data: "code="+ code,
success: function(msg){
$("#status").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#code").removeClass('object_error'); // if necessary
$("#code").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#code").removeClass('object_ok'); // if necessary
$("#code").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="red">The code should have at least <strong>2</strong> characters.</font>');
$("#code").removeClass('object_ok'); // if necessary
$("#code").addClass("object_error");
}
});
});
//-->
</SCRIPT><SCRIPT type="text/javascript">
<!--
pic1 = new Image(16, 16);
pic1.src = "loader.gif";
$(document).ready(function(){
$("#name").change(function() {
var code = $("#name").val();
if(code.length >= 0)
{
$("#stat_2").html('<img src="loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "check_con.php",
data: "name="+ name,
success: function(msg){
$("#stat_2").ajaxComplete(function(event, request, settings){
if(msg == 'OK')
{
$("#name").removeClass('object_error'); // if necessary
$("#name").addClass("object_ok");
$(this).html(' <img src="tick.gif" align="absmiddle">');
}
else
{
$("#name").removeClass('object_ok'); // if necessary
$("#name").addClass("object_error");
$(this).html(msg);
}
});
}
});
}
else
{
$("#stat_2").html('<font color="red"><strong>The name cannot be empty</strong></font>');
$("#name").removeClass('object_ok'); // if necessary
$("#name").addClass("object_error");
}
});
});
//-->
</SCRIPT>
</head>
<body id="main_body" >
<img id="top" src="form2/top.png" alt="">
<div id="form_container">
<h1><a>Country</a></h1>
<form id="country" class="appnitro" enctype="multipart/form-data" method="post" onsubmit="return checkForm()">
<div class="form_description">
<h2>Country</h2>
</div>
<table border ="0px" width="100%">
<tr>
<td><label class="description" for="element_1">Code</label></td><td><input id="code" name="code" type="text" maxlength="6" Placeholder="Please enter a code" value=""/></td><td width="400" align="left"><div id="status"></div></td>
</tr>
<tr>
<td><label class="description" for="element_1">Name</label></td><td><input id="name" name="name" size="40" type="text" maxlength="40" Placeholder="Please enter a name" value=""/></td><td width="400" align="left"><div id="stat_2"></div></td>
</tr>
<tr>
<td></td><td ><input type="submit" name="save" value="Save"></td>
</tr>
</table>
</form>
Here is my php code. It works fine for the code field but doesn't work for name.
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'pts_root';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
if(isSet($_POST['code']))
{
$code = $_POST['code'];
$sql_check = mysql_query("SELECT * FROM country WHERE code='".$code."'") or die(mysql_error());
if(mysql_num_rows($sql_check))
{
echo '<font color="red">The code <STRONG>'.$code.'</STRONG> is already exist.</font>';
}
else
{
echo 'OK';
}
}
?>
<?php
$dbHost = 'localhost'; // usually localhost
$dbUsername = 'root';
$dbPassword = '';
$dbDatabase = 'pts_root';
$db = mysql_connect($dbHost, $dbUsername, $dbPassword) or die ("Unable to connect to Database Server.");
mysql_select_db ($dbDatabase, $db) or die ("Could not select database.");
if(isSet($_POST['name']))
{
$name = $_POST['name'];
$sql_check = mysql_query("SELECT * FROM country WHERE UPPER(`name`)='".$name."'") or die(mysql_error());
if(mysql_num_rows($sql_check))
{
echo '<font color="red">The name <STRONG>'.$name.'</STRONG> is already exist.</font>';
}
else
{
echo 'OK';
}
}
?>
I'm looking at this particular section:
$sql_check = mysql_query("SELECT * FROM country WHERE UPPER(`name`)='".$name."'") or die(mysql_error());
if(mysql_num_rows($sql_check))
Without reading through all of the rest of your code, and trying to figure out your test case, it might be helpful for you to know that MySQL can use a "case insensitive" collation.
The UPPER function will convert the value stored to uppercase, but that doesn't really affect the comparison if the collation is case insensitive.
You may want to consider using the BINARY operator.
SELECT * FROM country WHERE BINARY UPPER(`name`)= 'FOO'
http://dev.mysql.com/doc/refman/5.5/en/charset-binary-op.html
One quick way to check the collation in MySQL is:
SHOW VARIABLES LIKE 'collation%'
You may see values like this:
utf8_general_ci
latin1_swedish_ci
That _ci at the end of the collation name identify this as a "case insensitive" collation, which basically means 'ABC' = 'abc' evaluates as TRUE.
Collation can be specified at the individual table and column level as well.
For more information, see the MySQL Reference http://dev.mysql.com/doc/refman/5.5/en/charset.html
NOTE: With php 5 and mysqli, do not use a SET names query, rather use the mysqli_set_charset.
http://php.net/manual/en/mysqli.set-charset.php
Change
$name = $_POST['name'];
to
$name = strtoupper($_POST['name']);
so you are comparing the capitalised input with the capitalised field.
You can also do it using like
SELECT * FROM country WHERE `name` like '$name'
Hope this helps

Categories