How I can have image with each result? I search many websites and many tutorials but I can't understand those tutorials.
here is my index
<nav>
<div class="nav-wrapper">
<form>
<div class="input-field">
<input id="vyhledat" class="form-control input-lg" type="search" placeholder="Vyhledat film..." />
<label class="label-icon" for="search"><i class="material-icons">search</i></label>
<i class="material-icons">close</i>
</div>
</form>
</div>
</nav>
here my script
<!-- js -->
<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>
$(document).ready(function(){
$('#vyhledat').autocomplete({
source: "php/vyhledat.php",
minLength: 3,
select: function(event, ui) {
var url = ui.item.id;
if (url != '#') {
location.href = url
}
},
open: function(event, ui) {
$(".ui-autocomplete").css("z-index", 1000)
}
})
});
</script>
And here is my php code
$keyword = trim($_REQUEST['term']); // input
$sugg_json = array();
$json_row = array();
$keyword = preg_replace('/\s+/', ' ', $keyword);
$query = 'SELECT id, nazev, href, obrazek FROM filmy WHERE nazev LIKE :term'; // query
$stmt = $DBcon->prepare( $query );
$stmt->execute(array(':term'=>"%$keyword%"));
if ( $stmt->rowCount()>0 ) {
while($recResult = $stmt->fetch(PDO::FETCH_ASSOC)) {
$json_row["id"] = $recResult['href'];
$json_row["value"] = $recResult['nazev'];
$json_row["label"] = $recResult['nazev'];
array_push($sugg_json, $json_row);
}
} else {
$json_row["id"] = "#";
$json_row["value"] = "";
$json_row["label"] = "Žádný výsledek";
array_push($sugg_json, $json_row);
}
$jsonOutput = json_encode($sugg_json, JSON_UNESCAPED_SLASHES);
print $jsonOutput;
and of course connection to my database.
$DBhost = "localhost";
$DBuser = "jirkua";
$DBpass = "koralek1";
$DBname = "jirkua";
try {
$DBcon = new PDO("mysql:host=$DBhost;dbname=$DBname",$DBuser,$DBpass);
$DBcon->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch(PDOException $ex){
die($ex->getMessage());
}`
Related
Here is the form View From
<form class="form-horizontal" role="form" id="frm_bulletin_board" method="post">
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1"> Title <font style="color:red;">*</font></label>
<div class="col-sm-9">
<input type="text" class="col-xs-12" name="txt_title" id="txt_title" />
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1"> Description <font style="color:red;">*</font></label>
<div class="col-sm-9">
<textarea id="txt_description" class="col-xs-12" name="txt_description" ></textarea>
</div>
</div>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-1">Upload Images </label>
<div class="col-sm-9">
<input type="file" class="col-xs-100" name="multiple_files" id="multiple_files" multiple />
<span id="error_multiple_files"></span>
</div>
</div>
</form>
function add_bulletin_board_with_images(){
var error_images = '';
var form_data = new FormData();
var files = $('#multiple_files')[0].files;
if(files.length > 10)
{
error_images += 'You can not select more than 10 files';
}
else
{
for(var i=0; i<files.length; i++)
{
var name = document.getElementById("multiple_files").files[i].name;
var ext = name.split('.').pop().toLowerCase();
//if(jQuery.inArray(ext, ['gif','png','jpg','jpeg']) == -1)
// {
// error_images += '<p>Invalid '+i+' File</p>';
// }
var oFReader = new FileReader();
oFReader.readAsDataURL(document.getElementById("multiple_files").files[i]);
var f = document.getElementById("multiple_files").files[i];
var fsize = f.size||f.fileSize;
if(fsize > 2000000)
{
error_images += '<p>' + i + ' File Size is very big</p>';
}
else
{
form_data.append("file[]", document.getElementById('multiple_files').files[i]);
}
}
}
if(error_images == '')
{
$.ajax({
url:"upload.php",
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
beforeSend:function(){
$('#error_multiple_files').html('<br /><img style="width:5%;" src="../assets/images/loader-gif.gif">');
},
success:function(data)
{
$('#error_multiple_files').html('');
$.gritter.add({
text: '<i class="fa fa-check"></i> Files uploaded successfully!',
class_name: 'gritter-success'
});
//document.getElementById("frm_bulletin_board").reset();
$('#multiple_files').val('');
}
});
}
else
{
$('#multiple_files').val('');
$('#error_multiple_files').html("<span class='text-danger'>"+error_images+"</span>");
return false;
}
}
php file upload.php
<?php
//////////db connection
session_start();
$db_servername = "localhost";
$db_username = "cwsp_user";
$db_password = "0cu1Fz3h02yHENYZ";
$db_name = "cwsp";
$conn = new mysqli($db_servername, $db_username, $db_password, $db_name);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//////////////////////////////
date_default_timezone_set('America/New_York');
$date = date('Y-m-d');
$date_time = date("Y-m-d h:i:s");
if(count($_FILES["file"]["name"]) > 0)
{
//$output = '';
sleep(3);
for($count=0; $count<count($_FILES["file"]["name"]); $count++)
{
$file_name = $_FILES["file"]["name"][$count];
$file_size =$_FILES['file']['size'][$count];
$tmp_name = $_FILES["file"]['tmp_name'][$count];
$file_array = explode(".", $file_name);
$file_extension = end($file_array);
if(file_already_uploaded($file_name, $conn))
{
$file_name = $file_array[0] . '-'. rand() . '.' . $file_extension;
}
$location = 'files/' . $file_name;
if(move_uploaded_file($tmp_name, $location))
{
$query = "
INSERT INTO bulletin_images
VALUES ('','1','','".$file_name."','', '".$file_size."','$date_time','Active','$_SESSION[ORGID]')
";
$statement = $conn->prepare($query);
$statement->execute();
}
}
}
function file_already_uploaded($file_name, $conn)
{
$query = "SELECT * FROM bulletin_images WHERE file_name = '".$file_name."'";
$result=$conn->query($query);
$number_of_rows = $result->num_rows;
if($number_of_rows > 0)
{
return true;
}
else
{
return false;
}
}
?>
i want to save title and description in MYSQL table named 'bulletin_board' and want to fill the last inserted id of bulletin board in the separate 'images' table, i can do this but i am stuck on figuring out how to pass title and description to the function add_bulletin_board_with_images()
thanks for all of your help but i found the solution by using form_data.append("param", "value") to add extra parameters in form_data
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 ";
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 😊
I want to link my json result to the google map. I have a imei_number in the database which is the password of the user. Once the user enter the right password(imei_number in the database), the system will select the longitude and latitude of the imei_number selected and later link it to the google map's longitude and latitude.
The HTML code is:
<form method="post" action="loginServer.php">
<label> Username: </label>
<input type = "text" maxlength = "20" name = "user" id= "user" />
<br />
<label> Password: </label>
<input type = "password" maxlength= "20" name="pass" id= "pass" />
<br />
<input type ="Button" onclick="" value="Clear" />
<input type = "Submit" value = "Login"id= "btn"/>
</p>
</form>
The Google map page is
<script type = "text/javascript">
function LoadMap(){
var mapEdit = {
zoom: 8,
center: new google.maps.LatLng($.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.latitude);
});
});
,
$.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.longitude);
});
});
),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), mapEdit);
var marker = new google.maps.Marker({
position: new google.maps.LatLng( $.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.latitude);
});
});
,
$.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.longitude);
});
});
),
map: map,
});
marker.addListener('click', function(){
infowindow.open(map, marker);
});
}
</script>
</head>
<body onload = "LoadMap()">
<div id="map" style="width: 400px; height: 500px;"></div>
The connect.php is
<?php
include 'linker.php';
$sql = "SELECT * FROM android_data WHERE $pass = 'imei_number'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
$row["longitude"]);
$row["longitude"]. " - latitude: " . $row["latitude"]. "<br>";
}
} else {
echo "0 results";
}
echo json_encode($data);
mysqli_close($conn);
?>
The linker.php is
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project_gps";
$user = $_POST['user'];
$pass = $_POST['pass'];
$user = stripcslashes($user);
$pass = stripcslashes($pass);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$user = mysqli_real_escape_string($conn, $user);
$pass = mysqli_real_escape_string($conn, $pass);
if($conn){
echo "connected";
}
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
But they are not all working. Please, what can I do?
So i already asked some questions here and fixed my problems,but i think they are growing instead of going down,lol.My problem now is i get "Undefined index" error.I will leave picture with the error here.I tried to add variables to define my fsearch.Tried things like
$fsearch = mysqli_escape_string($connect, $_POST['fsearch']);
And more simple like.
$fsearch = $_POST['fsearch'];
But it doesn't work.Here is code.
jQuery(document).ready(function ($) {
$("#food_search").keyup(function(event){
var search_term =$(this).val();
$.ajax({
type:"POST",
url:"/Food-Search",
data:{fsearch:search_term},
success:function(res){
$("#food_search_result").html(res);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!----------------------------------------------------------------
HTML
----------------------------------------------------------------->
<form method="POST">
<p>Търсене на храни: <input type="text" name="fsearch" id="food_search"></p>
</form>
<!----------------------------------------------------------------
PHP
-----------------------------------------------------------------><?php
$hostname = "localhost";
$username = "name";
$password = "password";
$databaseName = "dbName";
$connect = mysqli_connect($hostname, $username, $password, $databaseName);
if (!empty($_POST['fsearch'])) {
$fsearch = mysqli_escape_string($connect, $_POST['fsearch']);
$req = $connect->prepare('SELECT * FROM food_data_bg WHERE title LIKE "%".$fsearch."%"');
$req->execute(array(
'fsearch'=>'%'.$_POST['fsearch'].'%'
));
if($req->rowCount()==0){
echo 'Не бяха намерени резултати!';
}
else{
while($foodsearch=$req->fetch()){
?>
<div class="search-result">
<img src="<?php echo $data['fimage']; ?>" class="fimage"/>
<span class="result-title"><?php echo $data['title'];?></span><br>
<span class="calories-total"><?php echo $data['calories total'];?></span><br>
</div>
<?php
}
}
}
?>
The code is used for searching,it must get the value of #food-search (input field) on every keyup and send it to PHP,which must check for matches in database and print it.(I think i got 1 more mistake by printing result in PHP page and returning it to java to print it in #food_search_result div)
Hope this helps.
PHP Code
$hostname = "localhost";
$username = "root";
$password = "";
$databaseName = "stackoverflow";
if (!empty($_POST['fsearch'])) {
$fsearch = $_POST['fsearch'];
$mysqli = new mysqli($hostname , $username, $password, $databaseName);
if($mysqli->connect_error)
{
die("$mysqli->connect_errno: $mysqli->connect_error");
}
$query = "SELECT * FROM food_data_bg where title LIKE ?";
$stmt = $mysqli->stmt_init();
if(!$stmt->prepare($query))
{
print "Failed to prepare statement\n";
}
else
{
$searchVar = "%" . $fsearch . "%";
$stmt->bind_param("s", $searchVar);
$stmt->execute();
$result = $stmt->get_result();
if(!$result->num_rows){
echo 'Не бяха намерени резултати!';
}
while ($row = $result->fetch_array())
{
?>
<div class="search-result" style='clear:both; border:1px solid red;'>
<img src="<?php //echo $row['fimage']; ?>" class="fimage"/>
<span class="result-title"><?php echo $row['title'];?></span><br>
<span class="calories-total"><?php echo $row['calories total'];?></span><br>
</div>
<?php
}
}
$stmt->close();
$mysqli->close();
}
HTML Code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function ($) {
$("#food_search").keyup(function(event){
var search_term =$(this).val();
console.log(search_term);
$.ajax({
type:"POST",
url:"Food-Search.php",
data:{fsearch:search_term},
success:function(res){
$("#food_search_result").html(res);
console.log(res);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(xhr.responseText);
alert(thrownError);
}
});
});
});
</script>
<!----------------------------------------------------------------
HTML
----------------------------------------------------------------->
<form method="POST">
<p>Търсене на храни: <input type="text" name="fsearch" id="food_search"></p>
</form>
<!----------------------------------------------------------------
PHP
----------------------------------------------------------------->
<div style="border:#FF0000;clear:both; padding:10px;min-height:300px;" id="food_search_result"></div>