spliting autocomplete value into 2 string for php function - php

The values in the Autocomplete are first name and last name. I need to divide them into two strings, fn and ln, and send them to a PHP function to calculate the result.
I'm not sure how to separate the name into two values and send them to another PHP function which calculates the relation between these two people need their first name and last name to determine their id.
<html>
<?php include ('relation.php');?>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$("#fname").autocomplete({
source: 'mysql.php'
});
});
$(function() {
$("#fname2").autocomplete({
source: 'mysql.php'
});
});
</script>
<div class="ui-widget">
<label for="skills">fist person: </label>
<input id="fname">
</div>
<div class="ui-widget">
<label for="skills">second person </label>
<input id="fname2">
</div>
<div class="ui-widget">
<label for="skills">Skills: </label>
<button id="search" onclick="">
</div>
?>
</html>
<?php
//database configuration
$dbHost = 'localhost:3308';
$dbUsername = 'root';
$dbPassword = '';
$dbName = 'village';
//connect with the database
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
//get search term
$searchTerm = $_GET['term'];
//get matched data from skills table
$query = $db->query("SELECT * FROM individual WHERE fname LIKE
'%".$searchTerm."%'");
while ($row = $query->fetch_assoc()) {
$data[] = $row['fname']." ".$row['lname'];
}
//return json data
echo json_encode($data);
?>
//relation.php
function calculate_relationship($a_id, $b_id)
function aggrandize_relationship($rel, $dist, $offset = 0) {
function lowest_common_ancestor($a_id, $b_id)
function lowest_common_ancestor($a_id, $b_id)
function get_ancestors($id, $dist = 0)
.....
function getid($fname,$lname){
$conn = OpenCon();
get matched data from skills table
$query = $conn->query("SELECT id FROM individual WHERE fname LIKE
'%".$fname."%' and lname LIKE '%".$lname."%'");
$row = $query->fetch_row();
return $row[0];8*/
}
if( $_GET['fn1'] && $_GET['ln1']&&$_GET['fn2'] && $_GET['ln2']) {
$relation=calculate_relationship(getid($_GET['fn1'],$_GET['ln1']),getid($_GET['f
n2'],$_GET['ln2']));
}
//$relation=calculate_relationship($_GET['fn1'],$_GET['fn2']);
if($relation!='')
echo " a is the " .$relation." of b ";
else
echo "There's no relation between a and b ";

Related

PHP + MySQL - Autocomplete from database not getting data from table

I'm having a small college project about discussion room service. Right now I'm being tasked to implement autocomplete feature of name that orders it. I already google some tutorials. I'm not sure what went wrong, when i try to type a name, there's no data being typed ahead.
Here's my form code:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$name = "pinjamruang";
$koneksi = mysqli_connect($host, $user, $pass, $name);
//Periksa apakah koneksi berhasil
if(mysqli_connect_errno()){
echo "Error: ";
echo mysqli_connect_error();
echo "<br /> Error Code: ";
echo mysqli_connect_errno();
die();
}
$sql = "SELECT * FROM ruangan
WHERE id = $_GET[id]";
$hasil = mysqli_query($koneksi,$sql);
$row = mysqli_fetch_assoc($hasil);
$sql2 = "SELECT * FROM shift
WHERE id = $_GET[shift]";
$hasil2 = mysqli_query($koneksi,$sql2);
$row2 = mysqli_fetch_assoc($hasil2);
?>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#typeahead" ).autocomplete({
source: 'typeaheads.php';
});
});
</script>
<h1> Konfirmasi Pemesanan Ruang <?php echo $row['kode']; ?></h1><br>
<form class="form-horizontal" action="process/process-order-ruang.php" method="post">
<div class="form-group">
<label for="inputNamaPemesan" class="col-sm-2 control-label">Nama</label>
<div class="col-sm-10">
<input type="text" name="nama_pemesan" class="form-control" id="typeahead" placeholder="Nama Pemesan">
</div>
</div>
<div class="form-group">
<label for="inputKeperluan" class="col-sm-2 control-label">Keperluan</label>
<div class="col-sm-10">
<select name="keperluan" class="form-control" id="inputKeperluan">
<option value="Diskusi Belajar">Diskusi Belajar</option>
<option value="Diskusi Tugas">Diskusi Tugas</option>
<option value="Dokumentasi">Dokumentasi</option>
<option value="Lain-lain">Lain-lain</option>
</select>
</div>
</div>
<div class="form-group">
<label for="inputWaktu" class="col-sm-2 control-label">Waktu</label>
<div class="col-sm-10">
<input type="text" class="col-sm-5" name="waktu" value="<?php $row2['shift'];
$timestamp = strtotime($row2['shift']);
$waktuk = date('H.i A', $timestamp);
$int = (int)$waktuk;
echo $int; ?>:00" disabled> - <input type="text" class="col-sm-5"value="<?php $row2['shift'];
$timestamp = strtotime($row2['shift']);
$waktuk = date('H.i A', $timestamp);
$int = (int)$waktuk;
echo $int+2; ?>:00" disabled>
</div>
</div>
<?php $shift = $_GET['shift'];
$ruangan = $_GET['id'];?>
<input type="hidden" value="<?php $int2 = (int)$shift;?>" name="shift">
<input type="hidden" value="<?php $int3 = (int)$ruangan;?>" name="ruangan">
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-primary">Pesan</button>
</div>
</div>
</form>
and here is my code which should return json data from my table
<?php
$host = "localhost";
$user = "root";
$pass = "";
$name = "pinjamruang";
$koneksi = mysqli_connect($host, $user, $pass, $name);
//connect with the database
//get search term
$searchTerm = $_GET['term'];
//get matched data from table
$query = $koneksi->query("SELECT * FROM user
WHERE nama LIKE '%".$searchTerm."%' ORDER BY nama ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['nama'];
}
//return json data
echo json_encode($data);
?>
Any help would be much appreciated. Thanks a lot!
Use below code in script. remove semicolon from source. You can use colon for other parameters.
<script>
$(function() {
$( "#typeahead" ).autocomplete({
source: 'typeaheads.php'
});
});
</script>

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

MaterializeCSS Autocomplete PHP MySQL

I need to make a autocomplete input in materialize css page,
I've tried this code but did not work. Do you have any idea how to make this possible?
From here Autocomplete Textbox using jQuery, PHP and MySQL
index.php
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function() {
$( "#skills" ).autocomplete({
source: 'search.php'
});
});
</script>
</head>
<body>
<div class="ui-widget">
<label for="skills">Skills: </label>
<input id="skills" type="text">
</div>
search.php
<?php
$dbHost = 'localhost';
$dbUsername = 'u969692298_dogs';
$dbPassword = 'dogs123';
$dbName = 'u969692298_dogs';
$db = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$searchTerm = $_GET['term'];
$query = $db->query("SELECT * FROM kennels WHERE name LIKE '%".$searchTerm."%' ORDER BY name ASC");
while ($row = $query->fetch_assoc()) {
$data[] = $row['name'];
}
echo json_encode($data);
?>
What about something like this:
The result from this snippet suggests country name when you start typing in input box with materialize css framework.
Example with API GET request
$(document).ready(function() {
//Autocomplete
$(function() {
$.ajax({
type: 'GET',
url: 'https://restcountries.eu/rest/v2/all?fields=name',
success: function(response) {
var countryArray = response;
var dataCountry = {};
for (var i = 0; i < countryArray.length; i++) {
//console.log(countryArray[i].name);
dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
}
$('input.autocomplete').autocomplete({
data: dataCountry,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<div class="input-field">
<input type="text" id="autocomplete-input" class="autocomplete" autocomplete="off" name="name">
<label for="autocomplete-input">Country Name</label>
</div>
</div>
</div>
Above code by Jaikhlang Brahma answer
Example with POST request
Jquery
$(document).ready(function() {
//Autocomplete
var inp_val = document.getElementById("myInput").value;
var dataString = "name="+inp_val;
$(function() {
$.ajax({
type: 'POST',
url: 'suggest-country.php',
data: dataString,
success: function(response) {
var countryArray = response;
var dataCountry = {};
for (var i = 0; i < countryArray.length; i++) {
//console.log(countryArray[i].name);
dataCountry[countryArray[i].name] = countryArray[i].flag; //countryArray[i].flag or null
}
$('input.autocomplete').autocomplete({
data: dataCountry,
limit: 5, // The max amount of results that can be shown at once. Default: Infinity.
});
}
});
});
});
HTML
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/css/materialize.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.98.2/js/materialize.min.js"></script>
<div class="row">
<div class="col s12">
<div class="input-field">
<input type="text" id="autocomplete-input" class="autocomplete" autocomplete="off" name="name">
<label for="autocomplete-input">Country Name</label>
</div>
</div>
</div>
PHP (suggest-country.php)
<?
header('Content-type: text/html; charset=UTF-8');
$dbHost = 'localhost';
$dbUsername = 'u969692298_dogs';
$dbPassword = 'dogs123';
$dbName = 'u969692298_dogs';
$conn = new mysqli($dbHost,$dbUsername,$dbPassword,$dbName);
$query = trim(str_replace(" ", " ", $_POST['name']));
$str = htmlspecialchars($query);
$q = filter_var($str, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH);
$sql = $conn->prepare("SELECT * FROM kennels WHERE name = ? ORDER BY name ASC");
$sql->bind_param("s", $q);
$sql->execute();
$rs = $sql->get_result();
$arr = array();
while($row = $rs->fetch_assoc()){
$arr["name"] .= $row["name"];
$arr["flag"] .= $row["flag"];
}
// echo "<pre>".json_encode($arr)."</pre>";
echo json_encode($arr);
?>
This PHP code is pretty secure and working nicely.
For more relevancy use MYSQL FULL TEXT SEARCH or replace this SQL query
$sql = $conn->prepare("SELECT * FROM kennels WHERE name = ? ORDER BY name ASC");
$sql->bind_param("s", $q);
$sql->execute();
To this
$sql = $conn->prepare("SELECT *, " . " MATCH(name) AGAINST(? IN BOOLEAN MODE) AS relevance " . " FROM kennels" . " ORDER BY relevance DESC LIMIT 8");
$sql->bind_param("s", $q);
$sql->execute();
$rs = $sql->get_result();
Hope this is helpful to you, I know how old this post is, but I want to help other newbies who are experiencing this problem.
Thank you 😊

Using a variable with a changing value in MySQL query?

I'm building a tagging system for a site I'm working on. I have a variable for the url of the image that changes as the user selects different pictures. I'm using a MySQL command to display 3 tags for the selected picture, but it isn't working if I give it that changing variable. However, if I manually insert a url of an image, the captions show. However, these will show no matter what picture you're on so that doesn't really help. If I store a url under a variable, that works too, but not with the one that changes all the time.
Here's the site.
I know this isn't very easy to understand, so please let me know if you want me to try re-explaining something or if you want me to include some of the code. Thanks!
EDIT: Ok, I'll retry here. First, here's the code:
<?php
$username = $_GET['username'];
session_start();
$_SESSION['username'] = $username;
//Database Information
$dbhost = "";
$dbname = "";
$dbuser = "";
$dbpass = "";
//Connect to database
mysql_connect ( $dbhost, $dbuser, $dbpass)or die("Could not connect: ".mysql_error());
mysql_select_db($dbname) or die(mysql_error());
//Do the query
$query = mysql_query("SELECT * FROM images ORDER BY idnum DESC LIMIT 5");
// Generate an array of all images.
$images = array();
while($image = mysql_fetch_array($query)) {
// Adds each image to the images array.
$images[] = $image;
}
$image['filename'] = $current_image;
$query_captions = mysql_query("SELECT * from captions WHERE image = '$current_image' ORDER BY idnum DESC LIMIT 3");
$captions = array();
while($caption = mysql_fetch_array($query_captions)) {
$captions[] = $caption;
}
?>
<?php
// Beginning attempt at a caption script.
?>
<html>
<head>
<title>Home - Site in Development</title>
<link rel="stylesheet" type="text/css" href="styles.css"/>
<script type="text/javascript">
// Switches the url to view large image.
function switchImageUrl(url, width, height) {
var x = document.getElementById('caption_selection');
var y = document.getElementById('caption_input');
var z = document.getElementById('input_value');
x.style.display = 'none';
y.style.display = 'none';
z.value = '';
document.getElementById('center_frame').style.backgroundImage = 'url' + '(' + url + ')';
document.getElementById('center_frame').style.width = width;
document.getElementById('center_frame').style.height = height;
}
</script>
<!--Toggles view of caption selection tools and resets after.-->
<script type="text/javascript">
function selectionToggle() {
var x = document.getElementById('caption_selection');
var y = document.getElementById('caption_input');
var z = document.getElementById('input_value');
if(x.style.display == 'block')
x.style.display = 'none';
else
x.style.display = 'block';
x.style.width = '75px';
x.style.height = '75px';
x.style.top = '0px';
x.style.left = '0px';
if(y.style.display == 'block')
y.style.display = 'none';
else
y.style.display = 'block';
z.value = '';
}
</script>
<script type="text/javascript">
function collectAttributes() {
var cap = document.getElementById('caption_selection');
var cw = document.getElementById('cap_width');
var ch = document.getElementById('cap_height');
var cl = document.getElementById('cap_left');
var ct = document.getElementById('cap_top');
cw.value = cap.style.width;
ch.value = cap.style.height;
cl.value = cap.style.left;
ct.value = cap.style.top;
}
</script>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(document).ready(function() {
$("#caption_selection").draggable({
containment : "#center_frame"
});
$("#caption_selection").resizable({
containment : "#center_frame"
});
});
</script>
</head>
<body onLoad="CalculateAllImageWidthes()">
<div id='account_links'>
<?php
if ($_SESSION['username']) {
echo "Welcome $username!";
} else { ?>
<a href='login.php'>Login</a> | <a href='register.php'>Register</a>
<?php } ?>
</div>
<h1>Picture Captions</h1>
<br/>
<br/>
<div id="left_bar">
Submit a picture here.
<hr/>
<h2>Top Images</h2>
<br/>
<div id="front_pg_images">
<?php foreach($images as $image) { ?>
<a onClick="switchImageUrl('<?php echo $image['filename']; ?>', '<?php echo $image['width']; ?>', '<?php echo $image['height']; ?>')"><img src="<?php echo $image['filename'];?>" width="72px" height="58px" id="front_pg_thumbnail"/></a>
<?php echo $image['name']." - by ".$image['submitter']; ?> <br/>
<br/>
<?php } ?>
</div>
</div>
<div id="center_frame" style="width: <?php echo $image['width']; echo "px" ?>; height: <?php echo $image['height']; echo "px" ?>; background-image: url('<?php echo $image['filename'];?>')" >
<?php foreach($captions as $caption) { ?>
<div id="set_caption" style="width:<?php echo $caption['width'].'px';?>;height:<?php echo $caption['height'].'px';?>; left:<?php echo $caption['posleft'].'px';?>; top:<?php echo $caption['postop'].'px';?>"><?php echo $caption['text'];?></div>
<?php } ?>
<div id="caption_selection" style="display:none">
</div>
</div>
<div id="toggle_select_container">
<input type="button" id="toggle_select" onClick="selectionToggle()" value="Caption"/>
<div id="caption_input" style="display:none">
<form action="postcaption.php" method="post" onSubmit="collectAttributes()">
<br/>
<textarea name="caption_text" cols="27" rows="4" id="input_value"></textarea><br/>
<input type="hidden" name="filename" value="<?php echo $image['filename'];?>"/>
<input type="hidden" name="width" value="" id="cap_width"/>
<input type="hidden" name="height" value="" id="cap_height"/>
<input type="hidden" name="left" value="" id="cap_left"/>
<input type="hidden" name="top" value="" id="cap_top"/>
<input type="submit" value="Post Caption"/>
</form>
</div>
</div>
</body>
</html>
It uses a JavaScript function to change the image when the user clicks on the thumbnail. Take note of the foreach. For everywhere else on the page, the $image['filename'] has worked perfectly for similar uses, but it just isn't working when I try to use it with this.

Categories