I am developing a web application in PHP with a MySql database, and made a search suggestion box with ajax.
The problem is that I can select the suggestions with my mouse and it auto completes but when I try to auto complete it with my keyboard (select it with arrow up arrow down and pressing enter) it does nothing.
Is this a problem of my css, ajax or just html??? Could you please help with this, All help is appreciated, Thanks.
Here is my code :
Ajax
$term = mysqli_real_escape_string($link, $_REQUEST['term']); if(isset($term)){
// Attempt select query execution
$sql = "SELECT * FROM something WHERE name LIKE '" . $term . "%' LIMIT 4";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<p>" . $row['name'] . "</p>";
}
// Close result set
mysqli_free_result($result);
} else{
echo "<p>No Results</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
} }
CSS
.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: 0px solid #CCCCCC;
border-top: none;
cursor: pointer;
background: #ffffff;
}
.result p:hover{
background: #f2f2f2;
}
JAVASCRIPT
$(document).ready(function(){
$('.search-box 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("something.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).parent(".result").empty();
}); });
HTML
<form align=center method='POST' action='index.php?cmd=list-something'>
<h1 class="text-center">Search</h1>
<div class="form-group">
<div class="input-group search-box">
<input class="form-control" type="text" autocomplete="off" name="search" id="search" placeholder="Search"/>
<div class="result"></div>
<span class="input-group-btn">
<button class="btn btn-success" type="submit"><span class="glyphicon glyphicon-search" aria-hidden="true"><span style="margin-left:10px;">Pesquisar</span></button>
</span>
</span>
</div>
</div>
</form>
Please refer this Autocomplete library docs.
You can implement normal AJAX for fetching records and render those records using Autocomplete library.
Related
I have been creating a small map with different positions for a fabric. My goal is to make sure I can drag 1, 2, 3 and 4 (persons) into a position (e.g. Production Leader) and save the position of the DIV into the MySQL Database. I want a global map so each person which visit this page will see the same.
I created different DIV's for each person (1, 2, 3 and 4) which are already in the database.
I'm stuck right now.. can somebody help me?
Fiddle: https://jsfiddle.net/fj1zgw2o/
Database connection and showing persons from the database:
function choosePerson() {
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, image, position FROM Persons";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div class="boxPersons posLeft" id="'. $row['id'] .'">'. $row['id'] .'</div>';
}
} else {
echo "0 results";
}
}
// Move the box into the corresponding id.
// When you load your boxPersons have each
// person an id column that matches what position they will be in.
$(".boxPersons").each(function(e){
var target = $(this).attr("data-id");
$("#"+target).append($(this));
});
$(".boxPersons").draggable({
revert: 'invalid',
containment: '.box',
cursor: 'move'
});
$(".openSpots, .box-persons").droppable({
accept: ".boxPersons",
drop: function(event, ui) {
var droppable = $(this);
var draggable = ui.draggable;
// Move draggable into droppable
draggable.appendTo(droppable);
draggable.css({
top: '0px',
left: '0px'
});
}
});
.box-content {
display: flex;
}
.toPlan {
width: 10%;
}
.overviewPlanning {
flex: 1;
}
.box-persons {
overflow: hidden;
border-radius: 4px;
border: 1px solid #d8d8d8;
}
.boxPersons {
width: 60px;
height: 72px;
padding: 5px;
margin: 10px;
text-align: center;
border: 1px solid #d8d8d8;
border-radius: 4px;
z-index: 99;
float: left;
background: #888;
}
.posLeft {
float: left;
}
.openSpots {
width: 60px;
height: 72px;
padding: 5px;
margin: 10px;
text-align: center;
border: 0.5px dashed #000000;
border-radius: 4px;
z-index: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
<header>
Header
</header>
<div class="box">
<div class="box-content">
<div class="toPlan">
<div class="productionLeader">
<strong>Production Leader</strong>
<div id="Leader" class="openSpots" id="openSpots">
</div>
<strong>Free</strong>
<div id="Free" class="openSpots positionFree">
</div>
<strong>Ill</strong>
<div id="Ill" class="openSpots positionIll">
</div>
<strong>Otherwise</strong>
<div id="Otherwise" class="openSpots positionOtherwise">
</div>
</div>
</div>
<div class="overviewPlanning">
Fabric map
</div>
</div>
<div class="box-persons">
Available collegues (to drag and drop into a spot)<br>When you load the data into this box change the id to match what was saved. You can use AJAX to keep everything synced.<br>
<div class="boxPersons" data-id='Free'>bob</div>
<div class="boxPersons" data-id='Ill'>marry</div>
<div class="boxPersons" data-id=''>mark</div>
</div>
</div>
<footer>
Footer
</footer>
Here are three tables that I need to sync together.
-Table 1 is People (name, email etc)
-Table 2 is Cars (brand, color etc)
-Table 3 is Ads (One ad containing info from Table 1 and Table 2)
What I basically want is for "TABLE 1" to be able to search for data from "TABLE 2". When the data is selected I want data from both TABLE 1 and TABLE 2 to be entered into TABLE 3.
When a user is logged in he should be able to search for a products in a search field and choose one product - THIS IS DONE AND WORKS.
The problem is that I don't know how to take the search result, in this example it would be a car. And via a submit button create an AD and enter data in TABLE 3 with the name and email from TABLE 1 and the car model and color from TABLE 2.
Here is the CODE for the FORM:
<!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(){
$('.search-box 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("adsToDb.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).parent(".result").empty();
});
});
</script>
</head>
<br>
<br>
<p>Search the product you want to sell</p>
<body>
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search product..." />
<div class="result"></div>
</div>
</body>
<br>
<br>
<br>
<br>
<br>
<br>
<form action="createAd.php" method="post">
Name: <input type="text" name="name"><br>
<input type="submit" name="fields" value="sell this product" />
<input type="hidden" name="fieldsCount" value="<?php echo $fields+1 ?>" />
</form>
</html>
HERE IS THE CODE FOR THE DB SEARCH
<?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=DB", "", "");
// 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 * FROM products WHERE product_name 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['product_name'] . "</p>";
}
} else{
echo "<p>No matches found";
}
}
} catch(PDOException $e){
die("ERROR: Could not able to execute $sql. " . $e->getMessage());
}
// Close connection
unset($pdo);
?>
You can use a hidden field which holds the id of the car inside the forloop of the search result and once user click on button to add to Ad table, already you have the loggedIn User ID and can get from the hidden field the car_id
<form action="createAd.php" method="post">
Name: <input type="text" name="name">
<input type="submit" name="fields" value="sell this product" />
<input type="hidden" name="fieldsCount" value="<?php echo $fields+1 ?>" />
**<input type="hidden" name="car_id" value="<?php echo $car_id ?>" />**
</form>
I am creating a web page which Finding out and Listing the Doctors in a Given Area.
My both php scripts are as below.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Doctor 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;
margin: 0 50%;
}
.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(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var term = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(term.length){
$.get("backend-search.php", {query: term}).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).parent(".result").empty();
});
});
</script>
</head>
<body>
Select Your City:
<select name="city_nname">
<option value="Udaipur">Udaipur</option>
<option value="Jaipur">Jaipur</option>
<option value="Jodhpur">Jodhpur</option>
<option value="Sikar">Sikar</option>
<option value="Surat">Surat</option>
<option value="Ahmedabad">Ahmedabad</option>
<option value="badoda">badoda</option>
<option value="Pune">Pune</option>
<option value="Bangalore">Bangalore</option>
</select>
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search doctor..." />
<button type="submit" class="btn">Search</button>
<div class="result"></div>
</div>
</body>
</html>
The above code is my search_form.php. now I want to list out the the doctors name which are belongs to city_nname only.
Here is my php back end code
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "demo_db");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$query = mysqli_real_escape_string($link, $_REQUEST['query']);
if(isset($query)){
// Attempt select query execution
$sql = "SELECT * FROM doctors WHERE doctor_name LIKE '" . $query . "%'";
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<p>" . $row['doctor_name'] . "</p>";
}
// Close result set
mysqli_free_result($result);
} else{
echo "<p>No matches found for <b>$query</b></p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// close connection
mysqli_close($link);
?>
Now I want a mysql query that takes city_nname and doctor_name(from search box) and then give the list of doctors which are belongs to that city.
Please add lines which are comment by "// Add this line" and Modify lines which are comment by "// Modify this line"
search_form.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Live Doctor 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;
margin: 0 50%;
}
.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(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var term = $(this).val();
var city_nname = $("#city_nname").val(); // Add this line
var resultDropdown = $(this).siblings(".result");
if(term.length){
$.get("backend-search.php", {query: term, city:city_nname}).done(function(data){ // Modify this line
// 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).parent(".result").empty();
});
});
</script>
</head>
<body>
Select Your City:
<select name="city_nname" id="city_nname"> <!-- Modify this line -->
<option value="Udaipur">Udaipur</option>
<option value="Jaipur">Jaipur</option>
<option value="Jodhpur">Jodhpur</option>
<option value="Sikar">Sikar</option>
<option value="Surat">Surat</option>
<option value="Ahmedabad">Ahmedabad</option>
<option value="badoda">badoda</option>
<option value="Pune">Pune</option>
<option value="Bangalore">Bangalore</option>
</select>
<div class="search-box">
<input type="text" autocomplete="off" placeholder="Search doctor..." />
<button type="submit" class="btn">Search</button>
<div class="result"></div>
</div>
</body>
</html>
backend-search.php
<?php
/* Attempt MySQL server connection. Assuming you are running MySQL
server with default setting (user 'root' with no password) */
$link = mysqli_connect("localhost", "root", "", "bbtest");
// Check connection
if($link === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
// Escape user inputs for security
$query = mysqli_real_escape_string($link, $_REQUEST['query']);
$city = mysqli_real_escape_string($link, $_REQUEST['city']); // Add this line
if(isset($query)){
// Attempt select query execution
$sql = "SELECT * FROM doctors WHERE doctor_name LIKE '" . $query . "%' AND city_nname='".$city."'"; // modify the table column name "city_nname" as like yours
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<p>" . $row['doctor_name'] . "</p>";
}
// Close result set
mysqli_free_result($result);
} else{
echo "<p>No matches found for <b>$query</b></p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// close connection
mysqli_close($link);
?>
How about SELECT * FROM doctors WHERE doctor_name LIKE 'doctor_name%' AND city_nname='city_nname'? I can't quite get the trouble you're having in elaborating a solution.
I am working on a project and here I need to fetch data from a MySQL database.
And I need to fetch only that data which contain 38.
For example - I have a table which contain user_from and user_to and msg. Okay, now I have to fetch all data if user_from contain 38.
So I am able to fetch it but the problem is that is it fetching only one row from database nut I want all row which contain user_from 38.
So Please help me.
As Fast As you can
Codes----
<?php
include 'navigation.php';
include 'conn.php';
if(!$_SESSION["login"]){
header("location:index.php");
die;
}
if ($_SESSION['SESS_MEMBER_ID']) {
$id = $_SESSION['SESS_MEMBER_ID'];
} else {
echo "Sorry We are unable to get your id";
}
echo "<center><button type='button' class='btn btn-default' id='myBtn'> Send a message </button></center>";
?>
<!DOCTYPE html>
<html>
<head>
<style>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
#-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
#keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* The Close Button */
.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-header {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
.modal-body {padding: 2px 16px;}
.modal-footer {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
select {
width: 100%;
}
</style>
</head>
<body>
<!-- Trigger/Open The Modal -->
<!-- The Modal -->
<div id="myModal" class="modal">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close">×</span>
<h2>Send a Message</h2>
</div>
<div class="modal-body">
<label for="Friends">Select Friends:</label>
<select id="country" name="country">
<option value="Select Friends">Select Friends...</option>
<option value="australia">Australia</option>
<option value="canada">Canada</option>
<option value="usa">USA</option>
</select>
<br> <br>
<textarea cols="149" rows="12"></textarea>
<button type='button' class='btn btn-default' id='myBtn' name="sendmsgnow"> Send Now </button>
</div>
<div class="modal-footer">
<h3>Modal Footer</h3>
</div>
</div>
</div>
<script>
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
</body>
</html>
<?php
$aquery = "SELECT * FROM register WHERE id='$id'";
$aresult = mysqli_query($conn,$aquery);
while ($row = mysqli_fetch_assoc($aresult)) {
$user_id[] = $row["id"];
}
if (isset($_POST["sendmsgnow"])) {
$query = "INSERT INTO chats (user_from,user_to,msg_body,userdate,usertime) VALUES ('$id','1','$message','')";
$result = mysqli_query($conn,$query);
if ($result) {
echo "Your Message has been sent";
}
}
$b_query = "SELECT * FROM chats WHERE user_from='$id'";
$b_result = mysqli_query($conn,$b_query);
while ($data = mysqli_fetch_array($b_result)) {
$messages[] = $data["msg_body"];
$user_from = $data["user_from"];
if($user_from==38){
$d_query = "SELECT * FROM register WHERE id='$user_from'";
$d_result = mysqli_query($conn,$d_query);
while ($fdata = mysqli_fetch_assoc($d_result)) {
$frname = $fdata["firstname"];
echo "$frname sent you a message <br> $messages[]";
}
}
}
?>
As I told in comments you can use a nested while loop for thisUpdated
while ($data = mysqli_fetch_array($c_result)) {
$messages[] = $data["msg_body"];
$user_from = $data["user_from"];
if($user_from==38){
$d_query = "SELECT * FROM register WHERE id='$user_from'";
$d_result = mysqli_query($conn,$d_query);
while ($fdata = mysqli_fetch_assoc($d_result)) {
$frname = $fdata["firstname"];
}
} //This is end of if
echo "$frname sent you a message <br> $messages[]";
}//This END of First while loop
I have wrote what I have understood. Hope it helps you
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
},