How to make an autocomplete search with flexsearch - php

In my case of studies, I must to create an autocomplete search with this script. My problem is how to call the database. I don't know.
I suppose I must create another file call search.php
My code
<head>
<script src="https://cdn.jsdelivr.net/gh/nextapps-de/flexsearch#master/dist/flexsearch.min.js"></script>
<script src="search.php"></script>
<style>
table{
width: 300px;
table-layout: fixed;
}
td, tr{
border: none;
}
input{
border: 1px solid #ddd;
border-radius: 3px;
outline: none;
background-color: #f5f5f5;
}
input, div{
padding:5px 5px;
width: 100%;
box-sizing: border-box;
}
#suggestions div{
padding: 10px 0;
border-bottom: 1px solid #ddd;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
</style>
</head>
<div><input type="text" placeholder="Search ..." onkeyup="show_results.call(this);"></div>
<div id="suggestions"></div>
</div>
<script>
(function(){
var index = new FlexSearch({
encode: "advanced",
tokenize: "reverse",
suggest: true
});
var container = document.getElementById("suggestions");
for(var i = 0; i < data.length; i++){
index.add(i, data[i]);
}
window.show_results = function(){
var results = index.search(this.value, 10);
var fragment = document.createDocumentFragment();
var entry, tmp;
for(var i = 0; i < results.length; i++){
entry = document.createElement("div");
entry.textContent = data[results[i]];
fragment.appendChild(entry);
}
while((tmp = container.firstChild)){
container.removeChild(tmp)
}
container.appendChild(fragment);
};
}());
</script>
my search.php, I tried this code, but on how to take the seach keywords make by someone.
<?php
$terms = strtolower($_GET["q"]);
$Qcheck = $Db->prepare('select distinct products_id as id,
products_description as description
from :table_products_description
where products_description LIKE :terms
limit 10
');
$Qcheck->bindValue(':terms', '%' . $terms . '%');
$Qcheck->execute();
$list = $Qcheck->rowCount() ;
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
$json_response = json_encode($array);
echo $json_response;
?>
I expect inside the input field the search result across the database

I would like to help you. First of all I cannot check your php code, so please check the php returns a json encoded string. Then the solution to your intend is as follow.
Replace the last line in search.php by these two:
header('Content-Type: text/javascript');
echo 'var data = ' . $json_response . ';';
That's all :)

Related

display php array as dropdown checkbox

I've one array, which is output of some function and size of array is dynamic. So, I want to put all array element as drop-down with checkbox. Can anyone is here to help?
<select name="per1" id="per1">
<option selected="selected">Choose one</option>
<?php
foreach($names as $name) { ?>
<option value="<?= $name['name'] ?>"><?= $name['name'] ?></option>
<?php
} ?>
</select>
$names is example array take your.
check this link also
How to create checkbox inside dropdown?
Note
Okay, I can provide you a pseudo-code to help get you started. I borrowed my code from my own web server along with code from CodePen. Please note that I did not test the code, so do feel free to modify the code.
Code
PHP
<div class="dropdown" data-control="checkbox-dropdown">
<label class="dropdown-label">Select categories.</label>
<ul class="article-category-list dropdown-list">
<?php if(count($categories) > 0) {
foreach ($categories as $category) { ?>
<li class="article-category-listitem dropd-wn-listoption">
<input name="cbcategories[]"
id="cb<?=$category["CategoryID"] ?>" type="checkbox"
class="article-list-cb"
value="<?=$category['CategoryID'] ?>" />
<label class="article-list-lbl"
for="cb<?=$category["CategoryID"] ?>">
<?=$category['CategoryName'] ?>
</label>
</li>
<?php }} ?>
</ul>
</div>
This is a code borrowed from the administration portion of my blog that I haven't gotten into website development for a long time.
So the $categories variable is a list of categories for a blog. If the $categories array is greater than 0, PHP will loop through the $categories and will write out HTML code inside an unordered list, which contains the ID and name of the category.
CSS
(Borrowed from CodePen)
.dropdown {
position: relative;
font-size: 14px;
color: #333;
.dropdown-list {
padding: 12px;
background: #fff;
position: absolute;
top: 30px;
left: 2px;
right: 2px;
box-shadow: 0 1px 2px 1px rgba(0, 0, 0, .15);
transform-origin: 50% 0;
transform: scale(1, 0);
transition: transform .15s ease-in-out .15s;
max-height: 66vh;
overflow-y: scroll;
}
.dropdown-option {
display: block;
padding: 8px 12px;
opacity: 0;
transition: opacity .15s ease-in-out;
}
.dropdown-label {
display: block;
height: 30px;
background: #fff;
border: 1px solid #ccc;
padding: 6px 12px;
line-height: 1;
cursor: pointer;
&:before {
content: '▼';
float: right;
}
}
&.on {
.dropdown-list {
transform: scale(1, 1);
transition-delay: 0s;
.dropdown-option {
opacity: 1;
transition-delay: .2s;
}
}
.dropdown-label:before {
content: '▲';
}
}
[type="checkbox"] {
position: relative;
top: -1px;
margin-right: 4px;
}
}
It looks to me the "&.on" class is for when dropdown is opened.
jQuery
Now this code is in jQuery format. If you want plain JavaScript code, let me know.
(function($) {
var CheckboxDropdown = function(el) {
var _this = this;
this.isOpen = false;
this.areAllChecked = false;
this.$el = $(el);
this.$label = this.$el.find('.dropdown-label');
this.$checkAll = this.$el.find('[data-toggle="check-all"]').first();
this.$inputs = this.$el.find('[type="checkbox"]');
this.onCheckBox();
this.$label.on('click', function(e) {
e.preventDefault();
_this.toggleOpen();
});
this.$checkAll.on('click', function(e) {
e.preventDefault();
_this.onCheckAll();
});
this.$inputs.on('change', function(e) {
_this.onCheckBox();
});
};
CheckboxDropdown.prototype.onCheckBox = function() {
this.updateStatus();
};
CheckboxDropdown.prototype.updateStatus = function() {
var checked = this.$el.find(':checked');
this.areAllChecked = false;
this.$checkAll.html('Check All');
if(checked.length <= 0) {
this.$label.html('Select Options');
}
else if(checked.length === 1) {
this.$label.html(checked.parent('label').text());
}
else if(checked.length === this.$inputs.length) {
this.$label.html('All Selected');
this.areAllChecked = true;
this.$checkAll.html('Uncheck All');
}
else {
this.$label.html(checked.length + ' Selected');
}
};
CheckboxDropdown.prototype.onCheckAll = function(checkAll) {
if(!this.areAllChecked || checkAll) {
this.areAllChecked = true;
this.$checkAll.html('Uncheck All');
this.$inputs.prop('checked', true);
}
else {
this.areAllChecked = false;
this.$checkAll.html('Check All');
this.$inputs.prop('checked', false);
}
this.updateStatus();
};
CheckboxDropdown.prototype.toggleOpen = function(forceOpen) {
var _this = this;
// The dropdown menu is opened.
if(!this.isOpen || forceOpen) {
this.isOpen = true;
this.$el.addClass('on');
$(document).on('click', function(e) {
if(!$(e.target).closest('[data-control]').length) {
_this.toggleOpen();
}
});
}
else {
// The dropdown menu is closed.
this.isOpen = false;
this.$el.removeClass('on');
$(document).off('click');
}
};
var checkboxesDropdowns = document.querySelectorAll('[data-control="checkbox-dropdown"]');
for(var i = 0, length = checkboxesDropdowns.length; i < length; i++) {
new CheckboxDropdown(checkboxesDropdowns[i]);
}
})(jQuery);
I'm not sure why a "_this" variable is needed, plus I'm not an expert in CSS regarding the use of "&" character such as "&.on" (looks to me like a nested class or something), but at least I can be of help.
Here's the source of the code borrowed from CodePen (some from HTML such as dropdown-list):
https://codepen.io/RobotsPlay/pres/pyNLdL
Update as of 2:15 AM EDT:
As a fallback, for those who turned off JavaScript or is using a NoScript extension in Firefox to browse the web safely, you might want to provide just a simple <select><option>...</option></select> code as provided by Tejas kothari's answer and wrap it in a <noscript>...</noscript> tag.
Example of <noscript> tag:
<noscript>
<label for="categories_noscript">
Categories:
</label>
<p>In Windows/Linux, do Ctrl+click or in macOS, do Cmd+click to select
more than one.</p>
<select name="categories_noscript[]" id="categories_noscript">
<option selected="selected">Choose one or more categories</option>
<?php if(count($categories) > 0) {
foreach($categories as $category) { ?>
<option value="<?=$category['CategoryID'] ?>">
<?=$category['CategoryName'] ?>
</option>
</select>
</noscript>
It's not a drop down combo box as provided in the code above, but at least people can submit a form with JavaScript disabled.

On click, remove image from multiple input field and upload remaining into database

I am developing a site which allow uploading multiple images for one id. But I want to upload images into text format into database and real image to my directory. But before uploading image into database I preview images using JavaScript's FileReader.
My problem is, when I click remove in preview image , that image should also be removed from images that I want to upload.
And second, that I don't know how to do this, when I click first time and select some images, then again
I select some images by clicking input field, the images selected second time is being uploaded into database instead of all.
Here are my codes
// image preview
$("#productImage").on("change", function(e) {
var files = e.target.files,
filesLength = files.length;
for (var i = 0; i < filesLength; i++) {
var f = files[i]
var fileReader = new FileReader();
fileReader.onload = (function(e) {
var file = e.target;
$('.image-preview').append("<div class=\"product-image\">" +
"<img class=\"image-thumb\" src=\"" + e.target.result +
"\" title=\"" + file.name + "\" + data-file = \"" + file.name +
"\"/>" +
"<br/><div class=\"remove-image\">❌ Remove</span>" +
"</div>");
$('.remove-image').click(function(e) {
$(this).parent('.product-image').remove();
});
});
fileReader.readAsDataURL(f);
}
});
.form-elements {
display: flex;
flex-direction: column;
justify-content: left;
padding: 10px 0;
}
.form-elements .input-label {
padding: 10px 0;
}
.input-label label {
font-family: sans-serif;
font-size: 20px;
color: #fff;
}
.image-preview {
display: flex;
flex-wrap: wrap;
padding: 10px 0;
margin-bottom: 5px;
}
.image-preview .product-image {
display: block;
margin: 5px 10px;
width: 150px;
text-align: center;
}
.image-preview .product-image .image-thumb {
width: 100%;
border-radius: 10px;
cursor: pointer;
}
.image-preview .product-image .remove-image {
padding: 5px;
margin: 5px 0;
border-radius: 10px;
font-family: sans-serif;
font-size: 15px;
background: #ff3636;
color: #fff;
cursor: pointer;
}
.image-preview .product-image .remove-image:hover {
background: red;
}
<script
src="https://code.jquery.com/jquery-3.4.1.js"
integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU="
crossorigin="anonymous"></script>
<!-- product images -->
<div class="form-elements outside">
<div class="input-label">
<label for="productName">Select product image(s)</label>
</div>
<div class="image-preview">
<!-- Images will be here -->
</div>
<input type="file" id="productImage" name="productImage[]" multiple />
</div>
PHP code snippet
<?php
//connection
$connect = mysqli_connect('localhost','root','','sahi_chuno_db');
$image = $_FILES['productImage']['name'];
$temp_image = $_FILES['productImage']['tmp_name'];
$product_id = 1;
for ($i=0; $i < count($image); $i++) {
$query = $connect->prepare("INSERT INTO `product_images` (`product_id`, `product_image`)
VALUES(?, ?)");
$query -> bind_param('is',$product_id, $image[$i]);
$run = $query -> execute();
if($run){
//move images to directory
move_uploaded_file($temp_image[$i], "../uploads/$image[$i]");
} else{
echo "Not uploaded";
}
}
?>
You can use
<button onclick = "myFunction()">Remove</button> /Remove button in preview
function myFunction() {
document.getElementById("productImage").value = "";
}
To clear the input field and if it is cleared it will not be uploaded.
Note : For more details Click Here

Updating SQL 'WHERE' based on JSON AJAX checkbox selection

I have an AJAX HTML page and a submit PHP page, which sends data from SQL to update HTML on page.
I have a list of films within a PHPMyAdmin MariaDB table. One of the columns is "channel". Channel will either say "NOWTV", "BBC", or "SKYTV". I want the user to be able to select the channel and for this to update.
If I check the array for 1 string - for example: skytv, the SQL pulls the data. However, if I want to change the WHERE clause, based on selection - the filtering does not work.
I've tried ".=where OR" to change the channel selection.
ajax.html
<html>
<style>
body {
padding: 10px;
}
h2 {
margin: 1em 0 0.3em 0;
color: #343434;
font-weight: normal;
font-size: 30px;
line-height: 40px;
font-fnuamily: 'Orienta', sans-serif;
}
#employees {
font-family: "Lucida Sans Unicode","Lucida Grande",Sans-Serif;
font-size: 12px;
background: #fff;
margin: 10px 10px 0 0;
border-collapse: collapse;
text-align: center;
float: left;
width: 100%;
}
#employees th {
font-size: 14px;
font-weight: normal;
color: #039;
padding: 4px 4px;
border-bottom: 1px solid #6678b1;
}
#employees td {
border-bottom: 1px solid #ccc;
color: #669;
padding: 8px 10px;
}
#employees tbody tr:hover td {
color: #009;
}
.slidecontainer {
width: 50%; /* Width of the outside container */
}
/* The slider itself */
.slider {
-webkit-appearance: none; /* Override default CSS styles */
appearance: none;
width: 50%; /* Full-width */
height: 25px; /* Specified height */
background: #d3d3d3; /* Grey background */
outline: none; /* Remove outline */
opacity: 0.7; /* Set transparency (for mouse-over effects on hover) */
-webkit-transition: .2s; /* 0.2 seconds transition on hover */
transition: opacity .2s;
}
/* Mouse-over effects */
.slider:hover {
opacity: 1; /* Fully shown on mouse-over */
}
.slider::-webkit-slider-thumb {
-webkit-appearance: none; /* Override default look */
appearance: none;
width: 25px; /* Set a specific slider handle width */
height: 25px; /* Slider handle height */
background: #000000; /* Square background */
cursor: pointer; /* Cursor on hover */
}
.slider::-moz-range-thumb {
width: 25px; /* Set a specific slider handle width */
height: 25px; /* Slider handle height */
background: #4CAF50; /* Green background */
cursor: pointer; /* Cursor on hover */
}
</style>
</head>
<body>
<input type="checkbox" id="nowtv" name="nowtv" >
<label for="nowtv">Now TV</label>
</div>
<div>
<input type="checkbox" id="skytv" name="skytv" >
<label for="skytv">Sky Movies</label>
</div>
<div>
<input type="checkbox" id="iplayer" name="iplayer" >
<label for="iplayer">BBC iPlayer</label>
</div>
<h2>Max Run-Time:</h2>
<div class="slidecontainer">
<input type="range" min="0" max="200" value="0" class="slider" id="runtime">
<p>Runtime: <span id="runtime_"></span></p>
</div>
<table id="employees">
<tbody>
</tbody>
</table>
<script>
var slider = document.getElementById("runtime");
var output = document.getElementById("runtime_");
output.innerHTML = slider.value;
slider.oninput = function() {
output.innerHTML = this.value;
}
/script>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<p id="record_count"></p>
<script>
function makeTable(data){
var tbl_body = "";
for (var i = 0; i < data.length; i++)
{
var tbl_row = "";
var t = i;
for (var j=0; j<4; j++)
{
//tbl_row +=("<td>" + data[i].tmdbid + "</td>");
tbl_row +=("<td><a href='new/" + data[i].tmdbid + "'><IMG SRC='webaddress"+ data[i].poster +"'></a></td>");
i++;
}
tbl_body += "<tr>"+tbl_row+"</tr>"
}
return tbl_body;
}
function getEmployeeFilterOptions(){
var opts = {
checkboxes: [],
sliderValue: null
};
$checkboxes.each(function(){
if(this.checked){
opts.checkboxes.push(this.name);
}
});
var slider = document.getElementById("runtime");
opts.sliderValue = slider.value;
return opts;
}
function updateEmployees(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: opts,
success: function(records){
console.log(records);
$('#employees tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input");
$checkboxes.on("change", function(){
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
</script>
</body>
</html>
submit.php
<?php
$pdo = new PDO(
'mysql:host=xxxxxxxx;dbname=xxxxxxxx', 'xxxxxxxx', 'xxxxxxxx'
);
$checkboxes = $_POST["checkboxes"];
$slider_value = $_POST["sliderValue"];
$select = 'SELECT *';
$from = ' FROM streaming';
$where = ' WHERE poster <>"" AND runtime <' . $slider_value . ' AND channel = "X" ';
if (in_array("nowtv", $checkboxes))
{
$where .= ' OR channel = "NOWTV" ';
}
if (in_array("skytv", $checkboxes))
{
$where .= ' OR channel = "SKYTV" ';
}
if (in_array("iplayer", $checkboxes))
{
$where .= ' OR channel = "BBC" ';
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
>
The output I am expecting is for the user to be able to select the checkboxes and runtime - to then update the films available.
The current output shows nothing. :(

Add 3rd level submenu from php mysql database

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

How to get ID on the fly with Ajax

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
},

Categories