UPDATE:
Using #kyeiti's solution, I managed to get the other info where I need it, but I'm unable to navigate; I can go back and forward on the left side, but I can't get the right side to update. Also, if this could be accomplished with a single external PHP file it would be great. To make things clear, I put the whole thing online, you can check it out here. Also, I updated the code sections to reflect the latest changes.
UPDATE 2:
After some more help from #kyeiti, I'm trying to get it working with only 1 external PHP. The JS code is exactly as per #kyeiti's updated answer, while my art.php (now the only external file) looks like below. When I open index.php, I get nothing related to the two divs in the code. I also tried inserting them into the index file itself, but obviously that didn't work either...
Current art.php:
<?php
$username = "root"; //mysql username
$password = ""; //mysql password
$hostname = "localhost"; //hostname
$databasename = '2199'; //databasename
//get pic id from ajax request
if(isset($_POST["pic"]) && is_numeric($_POST["pic"]))
{
$current_picture = filter_var($_POST["pic"], FILTER_SANITIZE_NUMBER_INT);
}else{
$current_picture=1;
}
//Connect to Database
$mysqli = new mysqli($hostname, $username, $password, $databasename);
if ($mysqli->connect_error){
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//get next picture id
$result = $mysqli->query("SELECT id FROM gola WHERE id > $current_picture ORDER BY id ASC LIMIT 1")->fetch_object();
if($result){
$next_id = $result->id;
}
//get previous picture id
$result = $mysqli->query("SELECT id FROM gola WHERE id < $current_picture ORDER BY id DESC LIMIT 1")->fetch_object();
if($result){
$prev_id = $result->id;
}
//get details of current from database
$result = $mysqli->query("SELECT artikel, slika1 FROM gola WHERE id = $current_picture LIMIT 1")->fetch_object();
if($result){
//construct next/previous button
$prev_button = (isset($prev_id) && $prev_id>0)?'<span class="glyphicon glyphicon-circle-arrow-left rujz"></span>':'';
$next_button = (isset($next_id) && $next_id>0)?'<span class="glyphicon glyphicon-circle-arrow-right rujz"></span>':'';
//output html
echo "<div id='loaded_picture'>";
echo "test"; // Put everything that goes into the picture div here
echo "</div>";
echo "<div id='loaded_text'>";
echo "test"; // And everything that goes into the text div here
echo "</div>";
}
Original post:
I have two main divs in my page, the left side displays a photo and the right side should display some info about a specific product.
I get all the data out of MySQL and managed to hack together a working solution to navigate. I can go forward and backward using next/prev buttons and the image changes.
Now for some code:
HTML (index.php):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="layout.css">
<link href='https://fonts.googleapis.com/css?family=Syncopate' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.post( "art.php", { pic: "1"}, function( data ) {
$("#picture").html( data );
});
$.post( "info.php", { id: "1"}, function( data ) {
$("#info").html( data );
});
$("#picture").on("click",".get_pic", function(e){
var picture_id = $(this).attr('data-id');
$("#picture").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "art.php", { pic: picture_id}, function( data ) {
$("#picture").html( data );
});
return false;
});
$("#info").on("click",".get_info", function(e){
var info_id = $(this).attr('data-id');
$("#info").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "info.php", { pic: info_id}, function( data ) {
$("#info").html( data );
});
return false;
});
});
</script>
<title>2199</title>
</head>
<body>
<div class="navbar-wrapper">
<div class="container"> <img src="logo.png" class="boxy"> </div>
</div>
<div class="jumbotron special">
<div id="picture" align="center"> </div>
</div>
<div class="jumbotron special2">
<div id="info" align="center"> </div>
</div>
</body>
</html>
HTML (art.php):
$username = "root"; //mysql username
$password = ""; //mysql password
$hostname = "localhost"; //hostname
$databasename = '2199'; //databasename
//get pic id from ajax request
if(isset($_POST["pic"]) && is_numeric($_POST["pic"]))
{
$current_picture = filter_var($_POST["pic"], FILTER_SANITIZE_NUMBER_INT);
}else{
$current_picture=1;
}
//Connect to Database
$mysqli = new mysqli($hostname, $username, $password, $databasename);
if ($mysqli->connect_error){
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//get next picture id
$result = $mysqli->query("SELECT id FROM gola WHERE id > $current_picture ORDER BY id ASC LIMIT 1")->fetch_object();
if($result){
$next_id = $result->id;
}
//get previous picture id
$result = $mysqli->query("SELECT id FROM gola WHERE id < $current_picture ORDER BY id DESC LIMIT 1")->fetch_object();
if($result){
$prev_id = $result->id;
}
//get details of current from database
$result = $mysqli->query("SELECT artikel, slika1 FROM gola WHERE id = $current_picture LIMIT 1")->fetch_object();
if($result){
//construct next/previous button
$prev_button = (isset($prev_id) && $prev_id>0)?'<span class="glyphicon glyphicon-circle-arrow-left rujz"></span>':'';
$next_button = (isset($next_id) && $next_id>0)?'<span class="glyphicon glyphicon-circle-arrow-right rujz"></span>':'';
//output html
echo '<div class="prod_img" style="background-image: url(pictures/';
echo $result->slika1;
echo '); background-size: contain; background-repeat: no-repeat; background-position: center center;">';
echo '<h3>';
echo $prev_button;
echo $result->artikel;
echo $next_button;
echo '</h3>';
echo '</div>';
}
HTML (info.php):
<?php
$username = "root"; //mysql username
$password = ""; //mysql password
$hostname = "localhost"; //hostname
$databasename = '2199'; //databasename
//get pic id from ajax request
if(isset($_POST["info"]) && is_numeric($_POST["info"]))
{
$current_info = filter_var($_POST["info"], FILTER_SANITIZE_NUMBER_INT);
}else{
$current_info=1;
}
//Connect to Database
$mysqli = new mysqli($hostname, $username, $password, $databasename);
if ($mysqli->connect_error){
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//get next picture id
$result2 = $mysqli->query("SELECT id FROM gola WHERE id > $current_info ORDER BY id ASC LIMIT 1")->fetch_object();
if($result2){
$next_id = $result2->id;
}
//get previous picture id
$result2 = $mysqli->query("SELECT id FROM gola WHERE id < $current_info ORDER BY id DESC LIMIT 1")->fetch_object();
if($result2){
$prev_id = $result2->id;
}
//get details of current from database
$result2 = $mysqli->query("SELECT artikel, slika1, slika2, slika3, dim1, dim2, dim3, obdelava, dodatno FROM gola WHERE id = $current_info LIMIT 1")->fetch_object();
if($result2){
//construct next/previous button
$prev_button = (isset($prev_id) && $prev_id>0)?'<span class="glyphicon glyphicon-circle-arrow-left rujz-wht"></span>':'';
$next_button = (isset($next_id) && $next_id>0)?'<span class="glyphicon glyphicon-circle-arrow-right rujz-wht"></span>':'';
//output html
echo '<div class="info">';
echo '<h3 style="color: #fff !important;">';
echo $prev_button;
echo $result2->artikel;
echo $next_button;
echo '</h3>';
echo '<br />';
echo '<p>';
echo $result2->slika1;
echo '<br />';
echo $result2->slika2;
echo '<br />';
echo $result2->slika3;
echo '<br />';
echo $result2->dim1;
echo '<br />';
echo $result2->dim2;
echo '<br />';
echo $result2->dim3;
echo '<br />';
echo $result2->obdelava;
echo '<br />';
echo $result2->dodatno;
echo '</p>';
echo '</div>';
}
CSS (shall you need it):
html, body {
height: 100%;
background-color: #fff;
font-size: 62.5%;
}
.special, .special .jumbotron {
height: 100%;
background-color: white;
border: 0px solid red;
margin-bottom: 0px !important;
}
.special2, .special2 .jumbotron {
height: 100%;
background-color: #62a70f;
border: 0.5rem solid #fff;
border-radius: 3rem;
margin-bottom: 0px !important;
padding: 1rem;
}
.logo {
border: 1px solid red;
width: 10%;
min-height: 100%;
position: relative;
height: 100%;
}
#picture {
border: 0px red solid;
height: 100%;
background: #fff;
}
.prod_img {
height: 100%;
}
h3 {
font-family: 'Syncopate', sans-serif;
font-size: 24px;
font-size: 2.4rem;
color: #62a70f;
}
.boxy {
border: 0.5rem solid white;
position: fixed;
bottom: 2.5%;
right: 5%;
width: 25%;
padding: 1rem;
/* height: 30rem;*/
background-color: rgba(64,64,64,1);
border-radius: 3rem;/* background-image: url(logo.png);
background-size: contain;
background-repeat: no-repeat;*/
}
#media (min-width:768px) {
.boxy {
border: 0.5rem solid white;
position: fixed;
bottom: 5%;
right: 45%;
width: 10%;
/* height: 30rem;*/
background-color: rgba(64,64,64,1);
border-radius: 3rem;/* background-image: url(logo.png);
background-size: contain;
background-repeat: no-repeat;*/
}
.navbar {
min-height: 10% !important;
max-height: 10% !important;
height: 10%;
background-image: url(logo.png);
background-size: contain;
background-repeat: no-repeat;
border: 0px solid green;
background-color: #0e0e0e;
animation-name: example;
animation-duration: 1s;
animation-timing-function: ease;
}
.navbar-header {
border: 0px solid green;
min-height: 100%;
}
.logo {
visibility: collapse;
}
.special, .special .jumbotron {
width: 50%;
float: left;
margin-bottom: 0px !important;
}
.special2, .special2 .jumbotron {
width: 50%;
float: left;
margin-bottom: 0px !important;
}
h3 {
font-size: 48px;
font-size: 4.8rem;
}
.rujz {
font-size: 36px;
font-size: 3.6rem;
color: #62a70f;
margin: 0.5em;
}
.rujz-wht {
font-size: 36px;
font-size: 3.6rem;
color: #fff;
margin: 0.5em;
}
}
#keyframes example {
0% {
bottom:-10%;
}
100% {
bottom:0%;
}
}
Now, my question is the following:
The image and product name display correctly inside <div id="picture" align="center"> </div>
What I want to accomplish is get other data from the database and display it in the other half of the screen. Since it all happens inside art.php, it's not as easy as typing echo $results->columnName, so I'd need a bit of help.
Thanks in advance :)
You could create an other file like art.php to display the data you need and add an other post to that file to your onclick-event.
This is how I would edited the javascript from index.php:
$(document).ready(function() {
$.post( "art.php", { pic: "1"}, function( data ) {
$("#picture").html( data );
});
$.post( "text.php", { id: "1"}, function( data ) {
$("#text").html( data );
});
$("#picture").on("click",".get_pic", function(e){
var picture_id = $(this).attr('data-id');
$("#picture").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "art.php", { pic: picture_id}, function( data ) {
$("#picture").html( data );
});
$.post( "text.php", { id: picture_id}, function( data ) {
$("#text").html( data );
});
return false;
});
});
I can't really say much about text.php, since I don't know what information you want to display (or how you want to display it).
Edit: If you want only one post and only one external file you could use jQuerys .find-Function to extract portions from the ajax-data.
Javascript:
$(document).ready(function() {
$.post( "art.php", { pic: "1"}, function( data ) {
$("#picture").html( $(data).find("#loaded_picture") );
$("#text").html( $(data).find("#loaded_text") );
});
$("#picture").on("click",".get_pic", function(e){
var picture_id = $(this).attr('data-id');
$("#picture").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "art.php", { pic: picture_id}, function( data ) {
$("#picture").html( $(data).find("#loaded_picture") );
$("#text").html( $(data).find("#loaded_text") );
});
return false;
});
});
And in the art.php:
//get pic id from ajax request
if(isset($_POST["pic"]) && is_numeric($_POST["pic"])) {
$current_picture = filter_var($_POST["pic"], FILTER_SANITIZE_NUMBER_INT);
} else {
$current_picture=1;
}
/* Put connect to database and other preparations here */
echo "<div>";
echo "<div id='loaded_picture'>";
// Put everything that goes into the picture div here
echo "</div>"
echo "<div id='loaded_text'>";
// And everything that goes into the text div here
echo "</div>";
echo "</div>";
By looking at your index.php i think you are having trouble updating your
$result->artikel
in the table section when you call another image in. If this is the case then you can do this wrap your $result->artikel in art.php file with a div like <div class="artikel">$result->artikel</div> and echo it. Now you can do this to update your table section with the new data.
$("#picture").on("click",".get_pic", function(e){
var picture_id = $(this).attr('data-id');
$("#picture").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "art.php", { pic: picture_id}, function( data ) {
$("#picture").html( data );
//you should give class name to p that's easy after to work
$("table thead th:nth-child(2) p").html($(".artikel").html());
});
return false;
});
This will update your table section also
Related
I need to get json menu from mysql database with three levels. I am getting 1st level and 2nd level. I need to display 3rd level. I have added index page and categories.php and actual treeview and the current result what I am getting now and also extract from database for database records.
How can I get 3rd level from the database to complete the menu as I have shown in the actual menu tree?
categories.php
<?php
include('db.php');
$sql = mysqli_query($db,"select cat_id,product from category where parent_id=0");
// parent_id categories node
$categories = array("Categories" => array());
while ($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)) {
$cat_id = $row['cat_id'];
$ssql = mysqli_query($db,"select cat_id,product from category where parent_id='$cat_id'");
// single category node
$category = array(); // temp array
$category["cat_id"] = $row["cat_id"];
$category["product"] = $row["product"];
//$category["media"] = $row["media"];
$category["sub_categories"] = array(); // subcategories again an array
while ($srow = mysqli_fetch_array($ssql,MYSQLI_ASSOC)) {
$subcat = array(); // temp array
$subcat["cat_id"] = $srow['cat_id'];
$subcat["product"] = $srow['product'];
// pushing sub category into subcategories node
array_push($category["sub_categories"], $subcat);
}
// pushing sinlge category into parent_id
array_push($categories["Categories"], $category);
}
echo ((isset($_GET['callback'])) ? $_GET['callback'] : "") . '(' . json_encode($categories) . ')';
?>
index.html
<!DOCTYPE html>
<html>
<head>
<title>Menu</title>
<style>
body{background-color:#f2f2f2}
h3{ font-family: "arial","sans-serif"; color: #E47911;margin:0px; padding:0px }
.shadow {
-moz-box-shadow: 0px 0px 5px #999;
-webkit-box-shadow: 0px 3px 5px #999;
box-shadow: 0px 0px 5px #999;
}
#menu_ul, #submenu_ul {
left: 0;
list-style-type: none;
margin: 0;
padding: 0;
position: absolute;
top: 0;
padding:15px;
width:170px;
}
#submenu_ul{margin-top:25px; width:270px;}
#menu_ul li, #submenu_ul li
{
color: #333333;
cursor: pointer;
font-family: "arial","sans-serif";
font-size: 12px;
line-height: 16px;
margin: 0;
padding: 10px 0 10px;
}
#menu_ul li:active, #menu_ul li:hover
{
color: #E47911;
font-weight: bold;
background: url("images/arrow.png") no-repeat right;
}
#submenu_ul li:active, #submenu_ul li:hover
{
color: #E47911;
font-weight: bold;
}
#menu_box
{
border-top:solid 3px #333;border-left:solid 1px #dedede;border-right:solid 1px #dedede;border-bottom:solid 1px #dedede;min-height:510px;width:200px;background-color:#fff;margin-left:20px;float:left;position:relative;z-index:300
}
#menu_slider
{
border-top:solid 3px #333;border-left:solid 1px #dedede;border-right:solid 1px #dedede;border-bottom:solid 1px #dedede;min-height:480px;background-color:#fff;margin-left:220px;position:absolute;width:200px;position:relative;z-index:200;display:none;padding:15px
}
.hidebox, .hideul{display:none}
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function()
{
$.getJSON("categories.php?callback=?", function(data)
{
$.each(data.Categories, function(i, category)
{
var subjsondata='';
$.each(category.sub_categories, function(i, sub_categories)
{
subjsondata += "<li>"+sub_categories.product+"</li>";
});
var jsondata ="<li id='"+category.cat_id+"' class='category'>"+category.product+"<ul id='hide"+category.cat_id+"' class='hideul' >"+subjsondata+"</ul></li>";
$(jsondata).appendTo("#menu_ul");
});
}
);
$(".category").live('mouseover',function(event){
$("#menu_slider").show();
var D=$(this).html();
var id=$(this).attr('id');
var V=$("#hide"+id).html();
var M=$("#hide"+id).attr("media");
$("#submenu_ul").html(V);
$("#menu_slider h3").html(D);
if(M!='null')
{
$("#menu_slider").css({"width": "200px"});
}
else
{
$("#menu_slider").css({"width": "200px"});
}
$("#menu_slider").css('background', 'url(backgrounds/' + M + ') #ffffff no-repeat right bottom');
});
//Document Click
$(document).mouseup(function()
{
$("#menu_slider").hide();
});
//Mouse click on sub menu
$("#menu_slider").mouseup(function()
{
return false
});
//Mouse click on my account link
$("#menu_box").mouseup(function()
{
return false
});
});
</script>
</head>
<body>
<div id='menu_box' class='shadow'>
<ul id='menu_ul'>
</ul>
</div>
<div id='menu_slider' class='sshadow'>
<h3></h3>
<ul id='submenu_ul'>
</ul>
</div>
</body>
</html>
Actual treeview:
This is what I am getting result now.
Extract from Mysql Database:
php:
function getCategories($db,$parent_id = 0){
$categories = [];
$sql = mysqli_query($db,"select cat_id,product from category where parent_id='$parent_id'");
while ($row = mysqli_fetch_array($sql,MYSQLI_ASSOC)) {
// single category node
$category = array(); // temp array
$category["cat_id"] = $row["cat_id"];
$category["product"] = $row["product"];
//$category["media"] = $row["media"];
$category["sub_categories"] = getCategories($db,$row["cat_id"]); // subcategories again an array
$categories[] = $category;
}
return $categories;
}
$categories = array("Categories" => getCategories($db,0));
echo ((isset($_GET['callback'])) ? $_GET['callback'] : "") . '' . json_encode($categories) . '';
js:
For js you can use same approach
This is my code
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
try {
$pdo = new PDO("mysql:host=localhost;dbname=hospital", "root", "");
// Set the PDO error mode to exception
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
die("ERROR: Could not connect. " . $e->getMessage());
}
// Attempt search query execution
try {
if (isset($_REQUEST['term'])) {
// create prepared statement
$sql = "SELECT am_first_name, am_middle_name,am_last_name FROM
admission_master WHERE am_ip_no LIKE :term";
$stmt = $pdo->prepare($sql);
$term = $_REQUEST['term'] . '%';
// bind parameters to statement
$stmt->bindParam(':term', $term);
// execute the prepared statement
$stmt->execute();
if ($stmt->rowCount() > 0) {
while ($row = $stmt->fetch()) {
// echo "<p>" . $row['am_ip_no'] . "</p>";
echo "<p>" . $row['am_first_name'] . "</p>";
echo "<p>" . $row['am_middle_name'] . "</p>";
echo "<p>" . $row['am_last_name'] . "</p>";
}
} else {
echo "<p>No matches found</p>";
}
}
} catch (PDOException $e) {
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close statement
unset($stmt);
// Close connection
unset($pdo);
?>
Font End Code Is
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PHP Live MySQL Database Search</title>
<style type="text/css">
body{
font-family: Arail, sans-serif;
}
/* Formatting search box */
.search-box{
width: 300px;
position: relative;
display: inline-block;
font-size: 14px;
}
.search-box input[type="text"]{
height: 32px;
padding: 5px 10px;
border: 1px solid #CCCCCC;
font-size: 14px;
}
.result{
position: absolute;
z-index: 999;
top: 100%;
left: 0;
}
.search-box input[type="text"], .result{
width: 100%;
box-sizing: border-box;
}
/* Formatting result items */
.result p{
margin: 0;
padding: 7px 10px;
border: 1px solid #CCCCCC;
border-top: none;
cursor: pointer;
}
.result p:hover{
background: #f2f2f2;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#h input[type="text"]').on("keyup input", function () {
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if (inputVal.length) {
$.get("sqlsearch.php", {term: inputVal}).done(function (data) {
// Display the returned data in browser
resultDropdown.html(data);
});
} else {
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function () {
$(this).parents(".search-
box").find('input[type="text"]').val($(this).text());
$(this).parents("#autoFill").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<body>
<div class="search-box" id="h">
<input type="text" placeholder="Search ..." />
<div class="result"></div>
</div>
<div id="autoFill">
<input type="text" placeholder="name automatically ..." />
<div class="res"></div>
</div>
</body>
</html>
How To search name from the database using id from ajax and set that name to the next field in the form automatically this means ajax response.
With help from some of you guys, I managed to partially get the functionality I wanted. Now I'm stuck again, and I'd need some more help.
Check the live version here, the code is below. What I need is:
-
Figure out how to switch to the next/previous product on both sides of the screen with a single click of the arrows. The left side works as expected, the right one doesn't switch in any case.
-
Make the results of slika1, slika2 and slika3 (they contain the filenames of three separate images) on the right side display as links that will switch the image on the left side.
-
Modify the code to prevent SQL injection attacks (optional at the moment, but it would be welcome)
I'm pretty sure the whole functionality could be contained in a single file to be called with POST, but I'm really not sure how to do it properly. That would be a bonus too!
Here's my code:
HTML (index.php):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<link rel="stylesheet" href="layout.css">
<link href='https://fonts.googleapis.com/css?family=Syncopate' rel='stylesheet' type='text/css'>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.post( "art.php", { pic: "1"}, function( data ) {
$("#picture").html( data );
});
$.post( "info.php", { id: "1"}, function( data ) {
$("#info").html( data );
});
$("#picture").on("click",".get_pic", function(e){
var picture_id = $(this).attr('data-id');
$("#picture").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "art.php", { pic: picture_id}, function( data ) {
$("#picture").html( data );
});
return false;
});
$("#info").on("click",".get_info", function(e){
var info_id = $(this).attr('data-id');
$("#info").html("<div style=\"margin:50px auto;width:50px;\"><img src=\"loader.gif\" /></div>");
$.post( "info.php", { pic: info_id}, function( data ) {
$("#info").html( data );
});
return false;
});
});
</script>
<title>2199</title>
</head>
<body>
<div class="navbar-wrapper">
<div class="container"> <img src="logo.png" class="boxy"> </div>
</div>
<div class="jumbotron special">
<div id="picture" align="center"> </div>
</div>
<div class="jumbotron special2">
<div id="info" align="center"> </div>
</div>
</body>
</html>
HTML (art.php):
$username = "root"; //mysql username
$password = ""; //mysql password
$hostname = "localhost"; //hostname
$databasename = '2199'; //databasename
//get pic id from ajax request
if(isset($_POST["pic"]) && is_numeric($_POST["pic"]))
{
$current_picture = filter_var($_POST["pic"], FILTER_SANITIZE_NUMBER_INT);
}else{
$current_picture=1;
}
//Connect to Database
$mysqli = new mysqli($hostname, $username, $password, $databasename);
if ($mysqli->connect_error){
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//get next picture id
$result = $mysqli->query("SELECT id FROM gola WHERE id > $current_picture ORDER BY id ASC LIMIT 1")->fetch_object();
if($result){
$next_id = $result->id;
}
//get previous picture id
$result = $mysqli->query("SELECT id FROM gola WHERE id < $current_picture ORDER BY id DESC LIMIT 1")->fetch_object();
if($result){
$prev_id = $result->id;
}
//get details of current from database
$result = $mysqli->query("SELECT artikel, slika1 FROM gola WHERE id = $current_picture LIMIT 1")->fetch_object();
if($result){
//construct next/previous button
$prev_button = (isset($prev_id) && $prev_id>0)?'<span class="glyphicon glyphicon-circle-arrow-left rujz"></span>':'';
$next_button = (isset($next_id) && $next_id>0)?'<span class="glyphicon glyphicon-circle-arrow-right rujz"></span>':'';
//output html
echo '<div class="prod_img" style="background-image: url(pictures/';
echo $result->slika1;
echo '); background-size: contain; background-repeat: no-repeat; background-position: center center;">';
echo '<h3>';
echo $prev_button;
echo $result->artikel;
echo $next_button;
echo '</h3>';
echo '</div>';
}
HTML (info.php):
<?php
$username = "root"; //mysql username
$password = ""; //mysql password
$hostname = "localhost"; //hostname
$databasename = '2199'; //databasename
//get pic id from ajax request
if(isset($_POST["info"]) && is_numeric($_POST["info"]))
{
$current_info = filter_var($_POST["info"], FILTER_SANITIZE_NUMBER_INT);
}else{
$current_info=1;
}
//Connect to Database
$mysqli = new mysqli($hostname, $username, $password, $databasename);
if ($mysqli->connect_error){
die('Error : ('. $mysqli->connect_errno .') '. $mysqli->connect_error);
}
//get next picture id
$result2 = $mysqli->query("SELECT id FROM gola WHERE id > $current_info ORDER BY id ASC LIMIT 1")->fetch_object();
if($result2){
$next_id = $result2->id;
}
//get previous picture id
$result2 = $mysqli->query("SELECT id FROM gola WHERE id < $current_info ORDER BY id DESC LIMIT 1")->fetch_object();
if($result2){
$prev_id = $result2->id;
}
//get details of current from database
$result2 = $mysqli->query("SELECT artikel, slika1, slika2, slika3, dim1, dim2, dim3, obdelava, dodatno FROM gola WHERE id = $current_info LIMIT 1")->fetch_object();
if($result2){
//construct next/previous button
$prev_button = (isset($prev_id) && $prev_id>0)?'<span class="glyphicon glyphicon-circle-arrow-left rujz-wht"></span>':'';
$next_button = (isset($next_id) && $next_id>0)?'<span class="glyphicon glyphicon-circle-arrow-right rujz-wht"></span>':'';
//output html
echo '<div class="info">';
echo '<h3 style="color: #fff !important;">';
echo $prev_button;
echo $result2->artikel;
echo $next_button;
echo '</h3>';
echo '<br />';
echo '<p>';
echo $result2->slika1;
echo '<br />';
echo $result2->slika2;
echo '<br />';
echo $result2->slika3;
echo '<br />';
echo $result2->dim1;
echo '<br />';
echo $result2->dim2;
echo '<br />';
echo $result2->dim3;
echo '<br />';
echo $result2->obdelava;
echo '<br />';
echo $result2->dodatno;
echo '</p>';
echo '</div>';
}
CSS:
html, body {
height: 100%;
background-color: #fff;
font-size: 62.5%;
}
.special, .special .jumbotron {
height: 100%;
background-color: white;
border: 0px solid red;
margin-bottom: 0px !important;
}
.special2, .special2 .jumbotron {
height: 100%;
background-color: #62a70f;
border: 0.5rem solid #fff;
border-radius: 3rem;
margin-bottom: 0px !important;
padding: 1rem;
}
.logo {
border: 1px solid red;
width: 10%;
min-height: 100%;
position: relative;
height: 100%;
}
#picture {
border: 0px red solid;
height: 100%;
background: #fff;
}
.prod_img {
height: 100%;
}
h3 {
font-family: 'Syncopate', sans-serif;
font-size: 24px;
font-size: 2.4rem;
color: #62a70f;
}
.boxy {
border: 0.5rem solid white;
position: fixed;
bottom: 2.5%;
right: 5%;
width: 25%;
padding: 1rem;
/* height: 30rem;*/
background-color: rgba(64,64,64,1);
border-radius: 3rem;/* background-image: url(logo.png);
background-size: contain;
background-repeat: no-repeat;*/
}
#media (min-width:768px) {
.boxy {
border: 0.5rem solid white;
position: fixed;
bottom: 5%;
right: 45%;
width: 10%;
/* height: 30rem;*/
background-color: rgba(64,64,64,1);
border-radius: 3rem;/* background-image: url(logo.png);
background-size: contain;
background-repeat: no-repeat;*/
}
.navbar {
min-height: 10% !important;
max-height: 10% !important;
height: 10%;
background-image: url(logo.png);
background-size: contain;
background-repeat: no-repeat;
border: 0px solid green;
background-color: #0e0e0e;
animation-name: example;
animation-duration: 1s;
animation-timing-function: ease;
}
.navbar-header {
border: 0px solid green;
min-height: 100%;
}
.logo {
visibility: collapse;
}
.special, .special .jumbotron {
width: 50%;
float: left;
margin-bottom: 0px !important;
}
.special2, .special2 .jumbotron {
width: 50%;
float: left;
margin-bottom: 0px !important;
}
h3 {
font-size: 48px;
font-size: 4.8rem;
}
.rujz {
font-size: 36px;
font-size: 3.6rem;
color: #62a70f;
margin: 0.5em;
}
.rujz-wht {
font-size: 36px;
font-size: 3.6rem;
color: #fff;
margin: 0.5em;
}
}
#keyframes example {
0% {
bottom:-10%;
}
100% {
bottom:0%;
}
}
As always, thanks in advance!
i suggest using the carousel in bootstrap, since it's much better than what you are trying to achieve using Javascript.
Also, your MySQL queries can be shortened and changed into a more efficient code, by using a whileloop to output in to different sections.
But to not complicate things,
I assume that you are trying to get 2 different sections, one with a image and another with infomation? If so, you would want to cycle between 2 same slideshow with the same function. To do this,
<div id="Section1">Description</div>
<div id="Section1">slika1</div>
<div id="Shift"> Next </div>
and having a seperate javascript to cycle through each section
$(document).ready(function () {
$("#Section1").cycle();
$("#shift").click(function () {
$("#Section1").cycle('next');
});
});
a live example could be viewed here : http://jquery.malsup.com/cycle/pager11.html
edit: i wrote this entire answer without understanding your code.. so.. further clarifications could help :)
I'm trying to get the autocomplete to be linked to another page on the server. here as follows:
<?php
if($_POST)
{
$q=$_POST['searchword'];
$q=addslashes($q);
if(strlen($q) >0) {
$sql_res=mysql_query("select `id`, `firstName`, `lastName`, `email`, `photo`, `phone` from contacts where user_id = '$_SESSION[user_id]' AND lower(concat_ws(' ', firstname, lastname)) like '%$q%' order by id LIMIT 5");
while($row=mysql_fetch_array($sql_res))
{
$id = $row['id'];
$firstName=$row['firstName'];
$lastName=$row['lastName'];
$photo=$row['photo'];
$phone=$row['phone'];
$email = $row['email'];
$b_firstName='<b>'.$q.'</b>';
$b_lastName='<b>'.$q.'</b>';
$final_firstName = str_ireplace($q, $b_firstName, $firstName);
$final_lastName = str_ireplace($q, $b_lastName, $lastName);
$img_src = base64_decode($photo);
$imgbinary = fread(fopen($img_src, "r"), filesize($img_src));
$img_str = base64_encode($imgbinary);
?>
<div class="display_box" align="left">
<img src=<?php echo "'data:image/jpg;base64,$img_str'";?> style="width:58px; height:48px; float:left; margin-right:6px;" />
<span class="name"><?php echo $final_firstName; ?></span> <?php echo $final_lastName; ?>
<br/>
<span style="font-size:9px; color:#999999"><?php echo $phone; ?></span>
<span style="font-size:9px; color:#999999"><br/><?php echo $email; ?></span>
</div>
<?php
}
}
}
?>
that's the search.php.
Now on the main page I have this in the header:
<script type="text/javascript" src="js/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search-text").keyup(function()
{
var inputSearch = $(this).val();
var dataString = 'searchword='+ inputSearch;
if(inputSearch!='')
{
$.ajax({
type: "POST",
url: "search.php",
data: dataString,
cache: false,
success: function(html)
{
$("#divResult").html(html).show();
}
});
}return false;
});
jQuery("#divResult").click(function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("put tag close div tag here").html($name).text();
$('#inputSearch').val(decoded);
});
jQuery(document).click( function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#divResult").fadeOut();
}
});
});
</script>
<style type="text/css">
.contentArea{
width:600px;
margin:0 auto;
}
#inputSearch
{
width:250px;
border:solid 1px #000;
padding:3px;
}
#divResult
{
position:absolute;
width:255px;
display:none;
margin-top:-1px;
border:solid 2px #dedede;
border-top:0px;
overflow:hidden;
border-bottom-right-radius: 6px;
border-bottom-left-radius: 6px;
-moz-border-bottom-right-radius: 6px;
-moz-border-bottom-left-radius: 6px;
box-shadow: 0px 0px 5px #999;
border-style: solid;
border-color: #333 #000000 #000000;
background-color: white;
}
.display_box
{
padding:4px; border-top:solid 1px #dedede;
font-size:12px; height:50px; line-height: 1.5;
}
.display_box:hover
{
background:#3399ff;
color:#FFFFFF;
cursor:pointer;
}
</style>
and this is the search bar:
<input class="search-text" id="inputSearch" name="search" type="text" placeholder="Search " value="" /><div id="divResult">
</div>
So basically what i'm trying to do is when a user searches and the auto complete comes up, they can click on the image/suggestion and it takes them to the page associated with that image.
Also if they click enter, the search will pick the first autocoplete and direct them to that page.
I'm new to javascript/jquery
First of all, you need to return unique data belongs to specific user in your ajax response.
For example, you can use user id. Your autocomplete item will be like;
<div class="display_box" align="left" id="<?php echo $id; ?>">
<img src=<?php echo "'data:image/jpg;base64,$img_str'";?> style="width:58px; height:48px; float:left; margin-right:6px;" />
<span class="name"><?php echo $final_firstName; ?></span> <?php echo $final_lastName; ?><br/>
<span style="font-size:9px; color:#999999"><?php echo $phone; ?></span>
<span style="font-size:9px; color:#999999"><br/><?php echo $email; ?></span>
</div>
When you clicked specific item, it will redirect related page. In your JS;
$(".display_box").on("click", function() {
var userId = $(this).attr("id");
window.location = "/user/" + userId;
});
I have a question for you to upgrade my knowledge.
I am trying to create an inline editing page, the data are stored in a database.
In the table "content" I create 2 fields for testing purpose, the "id" and the "text" field.
If I want to modify the field with the "id=25" or id=X, I know how to do it manually, just specify in the MySQL Query "WHERE id=25", but if I have a list of 1000 entries, how can I modify the query to get the ID on the fly?
Here is the code, I am playing on:
index.php file
<style>
body {
font-family: Helvetica,Arial,sans-serif;
color:#333333;
font-size:13px;
}
h1{
font-family: Georgia, Times, serif;
font-size: 28px;
}
a{
color: #0071D8;
text-decoration:none;
}
a:hover{
text-decoration:underline;
}
:focus {
outline: 0;
}
#wrap{
width: 500px;
margin:0 auto;
overflow:auto;
}
#content{
background: #f7f7f7;
border-radius: 10px;
}
#editable {
padding: 10px;
}
#status{
display:none;
margin-bottom:15px;
padding:5px 10px;
border-radius:5px;
}
.success{
background: #B6D96C;
}
.error{
background: #ffc5cf;
}
#footer{
margin-top:15px;
text-align: center;
}
#save{
display: none;
margin: 5px 10px 10px;
outline: none;
cursor: pointer;
text-align: center;
text-decoration: none;
font: 12px/100% Arial, Helvetica, sans-serif;
font-weight:700;
padding: 5px 10px;
-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;
color: #606060;
border: solid 1px #b7b7b7;
background: #fff;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#ededed));
background: -moz-linear-gradient(top, #fff, #ededed);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#ededed');
}
#save:hover
{
background: #ededed;
background: -webkit-gradient(linear, left top, left bottom, from(#fff), to(#dcdcdc));
background: -moz-linear-gradient(top, #fff, #dcdcdc);
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffff', endColorstr='#dcdcdc');
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
$("#save").click(function (e) {
var content = $('#editable').html();
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: content
},
success:function (data) {
if (data == '1')
{
$("#status")
.addClass("success")
.html("Data saved successfully")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
else
{
$("#status")
.addClass("error")
.html("An error occured, the data could not be saved")
.fadeIn('fast')
.delay(3000)
.fadeOut('slow');
}
}
});
});
$("#editable").click(function (e) {
$("#save").show();
e.stopPropagation();
});
$(document).click(function() {
$("#save").hide();
});
});
</script>
</head>
<body>
<div id="wrap">
<div id="status"></div>
<div id="content">
<div id="editable" contentEditable="true">
<?php
//get data from database.
include("db.php");
$sql = mysql_query("select * from content");
$row = mysql_fetch_array($sql);
echo $row['id'];
echo "<br />";
echo $row['text'];
?>
</div>
<button id="save">Save</button>
</div>
</div>
</body>
And here is the save.php file:
include("db.php");
$content = $_POST['content']; //get posted data
$content = mysql_real_escape_string($content); //escape string
$sql = "UPDATE content SET text = '$content' WHERE id = '$id' ";
if (mysql_query($sql))
{
echo 1;
}
I know that this could be a stupid question but I am a newbie.
Thank you in advance for the help.
UPDATE:
thanx to Luis I fixed my old problem but I don't know why if I put all the code in a while only the "Save" button of the first entry is working good, the rest not, any hint?
At the moment I am testing only "description_text".
Here is the "while" code:
<?php
/////////// Now let us print the table headers ////////////////
$query =" SELECT * FROM gallery ORDER BY id DESC ";
$result = mysql_query($query) or die(mysql_error());
echo "<div style='width: 100%; text-align: center;'>";
echo "<table style='margin: auto auto;'>";
echo "<tr><th>ID</th><th>Image</th><th>Category</th><th>Description</th><th>Added on</th></tr>";
while($ordinate = mysql_fetch_array($result))
{
$id = $ordinate['id'];
$img_name = $ordinate['img_name'];
$category = $ordinate['category'];
$description_text = $ordinate['description_text'];
$insert_datetime = $ordinate['insert_datetime'];
echo "<tr><td style='width: 20px;'>".$id."</td><td style='width: 210px;'><img src='../../upload/content/uploaded_images/". $img_name ."' width='200px'></td><td style='width: 100px;'>".$category."</td><td style='width: 100px;'><div id='status'></div><div id='content'><div id='editable' contentEditable='true'>".$description_text."</div><button id='save'>Save</button></div></td><td style='width: 100px;'>".$insert_datetime."</td></tr>";
}
echo "</table><br /><br /></div>";
?>
on index.php move this part of code to the beginning, so you can use same vars in the rest of the script.
<?php
//get data from database.
include("db.php");
$sql = mysql_query("select * from content");
$row = mysql_fetch_array($sql);
// echo $row['id']; but keep this ones in its original place inside their <%php %> tags
// echo "<br />";
// echo $row['text'];
?>
Later in the ajax call, insert this PHP lines:
data: {
content: content
<?php
echo ", id: ".$row['id'];
echo ", token: '".md5('my SALT text'.(int)$row['id'])."'"; // strongly!!! recomended, not mandatory
?>
},
and on save.php
$id = (int)$_POST['id']; // (int) sanitizes id
$token = $_POST['token'];
if(md5('my SALT text'.$id)!=$token) die(); // or whatever but do not execute update
// perhaps echo 0; die();
// ... rest of your code ....
$sql = "UPDATE content SET text = '$content' WHERE id = $id"
the token, prevents the risk that someone uses your save.php as a way to inject whatever on every post on the table.
At least, an advice: use mysqli_query (notice the i) instead of mysql_query as this last is deprecated. Also, but with more diferences, you can use PDO
Instead of simply echoing the $row['id'], echo it inside an HTML element with specific id, so that it can be accessed from jQuery and can be posted.
<span id="idfield"><?php echo $row['id']; ?></span>
<button id="save">Save</button>
</div>
Then, inside the javascript :
$("#save").click(function (e) {
var content = $('#editable').html();
var id = $('#idfield').html();
Use it as a parameter in POST:
$.ajax({
url: 'save.php',
type: 'POST',
data: {
content: content,
id: id
},