I have homework to do in 2 days. I have already been trying to do this for 4 days but I'm not able to make this work, so I wanted to ask you for advice. Nothing that I try leads me to what I need. I am making a shop and I already have made a login register, a product display, but I'm missing one thing.
When the user enters the product page he/she can choose the color of the product. For example if the user wants a gold iPhone, and clicks on the side of a black iPhone, the side will turn gold. The pictures should be stored in a MySQL database, so that when the user clicks "order now" on it says "Gold iPhone."
Code : https://codeshare.io/UbKVU
I try to at least make echo so I can get it into database .. But nonthing .( I know its stupide idea but ... )
Ok, this is the client-side portion of managing a cart using json data (which you can create via php and a mysql table. I'll lay out the PHP/SQL Schema side of things as well.
Here's the codepen working example: https://codepen.io/xonosnet/pen/xeoYLz
var checkout = {
items: [],
total: 0.00
};
var phones = [
{
title: 'iPhone 7',
model: 'MHCPL6',
price: 625.22,
selectedColor: '',
colors: {
'White' : '255,255,255',
'Black' : '0,0,0',
'Gray' : '127,127,127',
'Pink' : '215,191,191'
},
images: {
'White' : 'https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/image/AppleInc/aos/published/images/M/QG/MQGX2/MQGX2?wid=2000&hei=2000&fmt=jpeg&qlt=95&op_usm=0.5,0.5&.v=1516399367562',
'Black' : 'https://www.att.com/shopcms/media/att/2017/shop/360s/8510273/6166B-1.jpg',
'Gray' : 'https://cloud.istyles.com/images/Skins/OSI7P/800/OSI7P-SS-GRY.jpg',
'Pink' : 'https://store.storeimages.cdn-apple.com/4982/as-images.apple.com/is/image/AppleInc/aos/published/images/M/QH/MQH22/MQH22?wid=2000&hei=2000&fmt=jpeg&qlt=95&op_usm=0.5,0.5&.v=1516399708457'
}
},
{
title: 'iPhone 8',
model: 'DDCNT7',
price: 785.22,
selectedColor: '',
colors: {
'White' : '255,255,255',
'Black' : '0,0,0',
'Gray' : '127,127,127',
'Red' : '225,0,0'
},
images: {
'White' : 'https://s3.envato.com/files/253291200/preview/preview1.jpg',
'Black' : 'https://img.tvc-mall.com/uploads/details/101112311A-1.jpg',
'Gray' : 'https://cloud.istyles.com/images/Skins/OSI7P/800/OSI7P-SS-GRY.jpg',
'Red' : 'https://img.tvc-mall.com/uploads/details/101112364C-1.jpg'
}
}
];
//Do a post frequest to pull this data out of the DB
//var phones = get_phones();
$.each(phones, function(index,phone) {
var phoneColors = get_phone_colors(index);
const htmlData = [
'<div class="phone" data-index="'+index+'">',
' <h2>'+phone.title+' <small>('+phone.model+')</small> <span class="price">$'+phone.price+'</span></h2>',
' <h4>Choose a color:</h4>',
' <div class="color-picker-ctn">',
' <div class="color-picker">'+phoneColors.colors+'</div>',
' <div class="phone-image" data-model="'+phone.model+'">'+phoneColors.default+'</div>',
' </div>',
' <button class="add-cart-btn">Add to Cart</button>',
'</div>'
];
$('.container').append(htmlData.join(''));
});
function get_phone_colors(i) {
var p = phones[i],
data = {
colors:'',
default:''
},
pass = 0;
console.log(p);
$.each(p.colors, function(index,c) {
var htmlOutput = '<div class="color '+(pass == 0 ? 'color-selected':'')+'" data-key="'+index+'" data-img="'+p.images[index]+'" data-model="'+p.model+'" data-index="'+i+'" style="background-color:rgb('+c+');"></div>';
console.log('IMG INDEX: '+i);
data.colors = data.colors+htmlOutput;
if(pass == 0) {
phones[i].selectedColor = index;
data.default = '<img src="'+p.images[index]+'"/>'
}
pass = pass+1;
});
return data;
}
function get_phones(phonedata = []) {
$.post('your_file.php', {get_phones:true}, function(data) {
phonedata = data;
},'json');
return phonedata;
}
$(document).on('click', '.color', function() {
var model = $(this).data('model'),
key = $(this).data('key'),
img = $(this).data('img'),
index = $(this).closest('.phone').data('index'),
model = phones[index].model;
console.log(img);
console.log("INDEX: "+index);
phones[index].selectedColor = key;
$('.color-selected').toggleClass('color-selected');
$(this).addClass('color-selected');
$('.phone-image[data-model="'+model+'"]').empty().append('<img src="'+img+'"/>');
});
$(document).on('click', '.add-cart-btn', function() {
var phone = phones[$(this).closest('.phone').data('index')];
checkout.items.push(phone);
checkout.total = checkout.total+phone.price;
update_cart();
});
var checkout = {
items: [],
total: 0.00
};
function update_cart() {
var htmlOutput = [];
checkout.total = 0.00;
if(checkout.items.length > 0) {
$.each(checkout.items, function(k,v) {
const output = [
'<div class="checkout-item">',
' <span>'+v.selectedColor+' '+v.title+' ('+v.model+')</span>',
' <span>$'+v.price+'</span>',
'</div>'
];
htmlOutput.push(output.join(''));
checkout.total = checkout.total+v.price;
});
$('.cart').empty().append(htmlOutput.join(''));
$('.cart').append('<h4>Total: $'+checkout.total.toFixed(2)+'</h4>');
} else {
checkout.total = 0.00;
}
}
.cart {
display:inline-block;
width:300px;
pading:50px;
vertical-align:top;
}
.container {
display:inline-block;
width:auto;
background-color:rgb(255,255,255);
pading:25px;
}
small {
font-size:14pt;
font-weight:normal;
}
.price {
float:right;
}
.phone {
display:inline-block;
width:400px;
height:500px;
background-color:#FFF;
border-radius:10px;
border:2px solid #CCC;
padding:10px;
margin:25px;
}
.color-picker-ctn {
display:block;
width:100%;
verticle-align:top;
valign:top;
background-color:#FFF;
}
.color-picker {
vertical-align:top;
display:inline-block;
width:25%;
}
.phone-image {
vertical-align:top;
display:inline-block;
width:70%;
border-raidus:15px;
overflow:hidden;
background-color:#FFF;
}
.phone-image img {
border-raidus:15px;
}
.color {
display:block;
width:80%;
height:55px;
border-radius:5px;
margin-bottom:5px;
vertical-align:top;
valign:top;
text-align:center;
border:4px solid rgb(0,0,0,.25);
transition:all ease 250ms;
}
.color:hover {
cursor:pointer;
transition:all ease 250ms;
border:4px solid rgb(255,0,0);
}
.color-selected {
border:4px solid rgb(0,255,0)!important;
}
.phone-image img {
display:block;
width:100%;
height:auto;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="cart">
<p>No items in cart yet.</P>
</div>
<div class="container">
</div>
Here's a simple table schema of how the database could look.
CREATE TABLE `products` (
`product_id` int(12) NOT NULL AUTO_INCREMENT,
`title` varchar(255) NOT NULL,
`model` varchar(50) DEFAULT NULL,
`price` decimal(6,2) DEFAULT '0.00',
PRIMARY KEY (`product_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE `product_colors` (
`option_id` int(12) NOT NULL AUTO_INCREMENT,
`product_id` int(12) NOT NULL,
`color_name` varchar(50) NOT NULL,
`color_rgb` varchar(11) DEFAULT '255,255,255',
`color_img` text,
`additional_cost` decimal(6,2) DEFAULT '0.00',
PRIMARY KEY (`option_id`),
KEY `product_id` (`product_id`),
CONSTRAINT `product_colors_ibfk_1` FOREIGN KEY (`product_id`) REFERENCES `products` (`product_id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Aaaand finally, here's a simple quick & dirty way of handling the PHP side of this. I did not include instructions on how to make a DB connection (in this example, I call it through $conn. Look up how to make PDO Mysql connections if you don't know how.
<?php
if(isset($_POST['get_phones']) {
$json = get_phones();
echo json_encode($json, JSON_PRETTY_PRINT);
}
function get_phones($return = array()) {
global $conn; //Your mysql connection object (using PDO)
$query = 'SELECT p.product_id, p.title, p.model, p.price FROM products as p';
$stmt = $conn->prepare($query);
$stmt->execute();
$rc = $stmt->rowCount();
if($rc > 0) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$colors = get_product_colors($row['product_id']);
$return[] = $row;
$return['colors'] = $colors['colors'];
$return['img'] = $colors['img'];
}
}
return $return;
}
function get_product_colors($pid, $return = array('colors'=>array(), 'img'=>array())) {
global $conn;
$query = 'SELECT p.option_id, p.color_name, p.color_rgb, p.color_img FROM product_colors as p WHERE p.product_id = '.$pid;
$stmt = $conn->prepare($query);
$stmt->execute();
$rc = $stmt->rowCount();
if($rc > 0) {
while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$return['colors'][$row['color_name']] = $row['color_rgb'];
$return['img'][$row['color_name']] = $row['color_img'];
}
}
return $return;
}
?>
Related
If you load XML links into https://www.convertcsv.com/xml-to-csv.htm (by using Enter URL), you immediately get a nice table:
How can you do it directly in PHP without knowing the XML's structure in advance?
Sample code and URL:
<?php
url = 'https://uxdb.s3.amazonaws.com';
$input = new SimpleXMLElement($url, 0, TRUE);
echo '<pre>' . print_r($input, true) . '<pre>';
?>
Which gives you:
Here's how I ended up doing it - https://paiza.io/projects/-ouYa8tFfqcH8QeaVeQfIw (this fiddle tester has a limit on output, so I used 5 instead of count($array) there):
<?php
$url = 'https://uxdb.s3.amazonaws.com';
$input = new SimpleXMLElement($url, 0, TRUE);
$json = json_encode($input);
$array = json_decode($json,TRUE)['Contents'];
header('Content-Type: text/html; charset=utf-8');
?>
<head>
<style>
table2 {
border-spacing: 0;
width: 100%;
border: 1px solid #ddd;
}
th {cursor: pointer;}
th, td {
text-align: left;
padding: 16px;
}
tr:nth-child(even) {
background-color: #f2f2f2
}
</style>
</head>
<body>
<table id="sortable">
<?php
for ($i=0; $i<count($array); $i++) {
if ($i==0)
echo "<thead>\n";
echo "<tr>\n";
foreach ($array[$i] as $key => $value)
echo ($i==0 ? "<th>$key ↕</th>" : "<td>" . ($key == 'Key' ? "$value" : $value) . "</td>") . "\n";
echo "</tr>\n";
if ($i==0)
echo "</thead>\n<tbody>\n";
}
?>
</tbody>
</table>
<script>document.addEventListener('DOMContentLoaded', function() {
const table = document.getElementById('sortable');
const headers = table.querySelectorAll('th');
const tableBody = table.querySelector('tbody');
const rows = tableBody.querySelectorAll('tr');
// Track sort directions
const directions = Array.from(headers).map(function(header) {
return '';
});
// Transform the content of given cell in given column
const transform = function(index, content) {
// Get the data type of column
const type = headers[index].getAttribute('data-type');
switch (type) {
case 'number':
return parseFloat(content);
case 'string':
default:
return content;
}
};
const sortColumn = function(index) {
// Get the current direction
const direction = directions[index] || 'asc';
// A factor based on the direction
const multiplier = (direction === 'asc') ? 1 : -1;
const newRows = Array.from(rows);
newRows.sort(function(rowA, rowB) {
const cellA = rowA.querySelectorAll('td')[index].innerHTML;
const cellB = rowB.querySelectorAll('td')[index].innerHTML;
const a = transform(index, cellA);
const b = transform(index, cellB);
switch (true) {
case a > b: return 1 * multiplier;
case a < b: return -1 * multiplier;
case a === b: return 0;
}
});
// Remove old rows
[].forEach.call(rows, function(row) {
tableBody.removeChild(row);
});
// Reverse the direction
directions[index] = direction === 'asc' ? 'desc' : 'asc';
// Append new row
newRows.forEach(function(newRow) {
tableBody.appendChild(newRow);
});
};
[].forEach.call(headers, function(header, index) {
header.addEventListener('click', function() {
sortColumn(index);
});
});
});</script>
I have some questions and i hope someone help me to solve it . the questions is:
1) i want to save the drawing polygon into database mysql.
2) each polygon can have different name and insert into database.
3) edit and delete the polygon that was created and save it into database.
in my code i'm using google map tool to draw and give color to each polygon was drawing on google map. so i hope someone help me of code about save all these into database. Thank you
code.
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false&libraries=drawing"></script>
<style type="text/css">
#map, html, body {
padding: 0;
margin: 0;
height: 100%;
}
#panel {
width: 200px;
font-family: Arial, sans-serif;
font-size: 13px;
float: right;
margin: 10px;
}
#color-palette {
clear: both;
}
.color-button {
width: 14px;
height: 14px;
font-size: 0;
margin: 2px;
float: left;
cursor: pointer;
}
#delete-button {
margin-top: 5px;
}
</style>
<script type="text/javascript">
var drawingManager;
var selectedShape;
var colors = ['#1E90FF', '#FF1493', '#32CD32', '#FF8C00', '#4B0082'];
var selectedColor;
var colorButtons = {};
function clearSelection() {
if (selectedShape) {
selectedShape.setEditable(false);
selectedShape = null;
}
}
function setSelection(shape) {
clearSelection();
selectedShape = shape;
shape.setEditable(true);
selectColor(shape.get('fillColor') || shape.get('strokeColor'));
}
function deleteSelectedShape() {
if (selectedShape) {
selectedShape.setMap(null);
}
}
function selectColor(color) {
selectedColor = color;
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
colorButtons[currColor].style.border = currColor == color ? '2px solid #789' : '2px solid #fff';
}
// Retrieves the current options from the drawing manager and replaces the
// stroke or fill color as appropriate.
var polylineOptions = drawingManager.get('polylineOptions');
polylineOptions.strokeColor = color;
drawingManager.set('polylineOptions', polylineOptions);
var rectangleOptions = drawingManager.get('rectangleOptions');
rectangleOptions.fillColor = color;
drawingManager.set('rectangleOptions', rectangleOptions);
var circleOptions = drawingManager.get('circleOptions');
circleOptions.fillColor = color;
drawingManager.set('circleOptions', circleOptions);
var polygonOptions = drawingManager.get('polygonOptions');
polygonOptions.fillColor = color;
drawingManager.set('polygonOptions', polygonOptions);
}
function setSelectedShapeColor(color) {
if (selectedShape) {
if (selectedShape.type == google.maps.drawing.OverlayType.POLYLINE) {
selectedShape.set('strokeColor', color);
} else {
selectedShape.set('fillColor', color);
}
}
}
function makeColorButton(color) {
var button = document.createElement('span');
button.className = 'color-button';
button.style.backgroundColor = color;
google.maps.event.addDomListener(button, 'click', function() {
selectColor(color);
setSelectedShapeColor(color);
});
return button;
}
function buildColorPalette() {
var colorPalette = document.getElementById('color-palette');
for (var i = 0; i < colors.length; ++i) {
var currColor = colors[i];
var colorButton = makeColorButton(currColor);
colorPalette.appendChild(colorButton);
colorButtons[currColor] = colorButton;
}
selectColor(colors[0]);
}
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(22.344, 114.048),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
zoomControl: true
});
var polyOptions = {
strokeWeight: 0,
fillOpacity: 0.45,
editable: true
};
// Creates a drawing manager attached to the map that allows the user to draw
// markers, lines, and shapes.
drawingManager = new google.maps.drawing.DrawingManager({
drawingMode: google.maps.drawing.OverlayType.POLYGON,
markerOptions: {
draggable: true
},
polylineOptions: {
editable: true
},
rectangleOptions: polyOptions,
circleOptions: polyOptions,
polygonOptions: polyOptions,
map: map
});
google.maps.event.addListener(drawingManager, 'overlaycomplete', function(e) {
if (e.type != google.maps.drawing.OverlayType.MARKER) {
// Switch back to non-drawing mode after drawing a shape.
drawingManager.setDrawingMode(null);
// Add an event listener that selects the newly-drawn shape when the user
// mouses down on it.
var newShape = e.overlay;
newShape.type = e.type;
google.maps.event.addListener(newShape, 'click', function() {
setSelection(newShape);
});
setSelection(newShape);
}
});
// Clear the current selection when the drawing mode is changed, or when the
// map is clicked.
google.maps.event.addListener(drawingManager, 'drawingmode_changed', clearSelection);
google.maps.event.addListener(map, 'click', clearSelection);
google.maps.event.addDomListener(document.getElementById('delete-button'), 'click', deleteSelectedShape);
buildColorPalette();
}
google.maps.event.addDomListener(window, 'load', initialize);
Ok, considering the broad nature to the question and lack of supporting structure / resources you will need to study and adapt if the following does what you need.
The first step would be to create the database structure you need - here I have created two, very basic, mySQL tables in a new database called gm_polygons. I'm not suggesting that these schemas will be sufficient for all the data that you need to store in the tables - such as colour, stroke, title etc etc but will give a starting point.
create table `paths` (
`id` int(10) unsigned not null auto_increment,
`pid` int(10) unsigned not null default '0',
`lat` float not null default '0',
`lng` float not null default '0',
primary key (`id`),
index `pid` (`pid`)
)
collate='utf8_general_ci'
engine=innodb;
create table `polygon` (
`id` int(10) unsigned not null auto_increment,
`name` varchar(50) not null default '0',
primary key (`id`)
)
collate='utf8_general_ci'
engine=innodb;
The php map page. The map loads, in this case centred upon London, and assigns a listener to the map which allows drawing of the polygon ( only polygons in this demo, no circles or polylines etc ) - the form has an input for the name of the poly and a button to send, via ajax, the details to the php script to process.
You could, after generating the db and tables shown here, modify the following byadding relevant details for host,user,password etc and run this to test.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* process the addition of the polygon */
if( !empty( $_POST['name'] ) && !empty( $_POST['path'] ) ){
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'gm_polygons';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$name=$_POST['name'];
$path=json_decode( $_POST['path'] );
/* insert new path */
$sql='insert into polygon set `name`=?';
$stmt=$db->prepare( $sql );
if( !$stmt )exit( 'Error: query 1' );
$stmt->bind_param('s',$name);
$stmt->execute();
$stmt->free_result();
$stmt->close();
/* get the ID for the newly inserted Polygon name */
$id=$db->insert_id;
/* add all the latlng pairs for the polygon */
$sql='insert into `paths` ( `pid`, `lat`, `lng` ) values ( ?, ?, ? )';
$stmt=$db->prepare( $sql );
if( !$stmt )exit( 'Error: query 2' );
$stmt->bind_param( 'idd', $id, $lat, $lng );
foreach( $path as $obj ){
$lat=$obj->lat;
$lng=$obj->lng;
$stmt->execute();
}
$stmt->close();
echo json_encode(
array(
'name'=>$name,
'points'=>count($path)
)
);
}
exit();
}
?>
<html>
<head>
<meta charset='utf-8' />
<title>Google Maps: Storing Polygons in database</title>
<script async defer src='//maps.google.com/maps/api/js?key=APIKEY-gFJ0&callback=initMap®ion=GB&language=en'></script>
<script>
let map;
let div;
let bttn;
let input;
let options;
let centre;
let poly;
let path;
let polypath;
function initMap(){
const ajax=function( url, params, callback ){
let xhr=new XMLHttpRequest();
xhr.onload=function(){
if( this.status==200 && this.readyState==4 )callback( this.response )
};
xhr.open( 'POST', url, true );
xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
xhr.send( buildparams( params ) );
};
const buildparams=function(p){
if( p && typeof( p )==='object' ){
p=Object.keys( p ).map(function( k ){
return typeof( p[ k ] )=='object' ? buildparams( p[ k ] ) : [ encodeURIComponent( k ), encodeURIComponent( p[ k ] ) ].join('=')
}).join('&');
}
return p;
};
const createpoly=function(){
poly=new google.maps.Polygon({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 3,
fillColor: '#FF0000',
fillOpacity: 0.35,
draggable:true,
editable:true
});
poly.setMap( map );
return poly;
};
centre=new google.maps.LatLng( 51.483719, -0.020037 );
div=document.getElementById('map');
input=document.querySelector('#container > form > input[name="polyname"]');
bttn=document.querySelector('#container > form > input[type="button"]');
options = {
zoom: 15,
center: centre,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU,
mapTypeIds: [ 'roadmap', 'terrain', 'satellite', 'hybrid' ]
}
};
map = new google.maps.Map( div, options );
createpoly();
google.maps.event.addListener( map, 'click', e=>{
path=poly.getPath();
path.push( e.latLng );
});
google.maps.event.addListener( poly, 'rightclick', e=>{
poly.setMap( null );
createpoly();
});
bttn.addEventListener('click',e=>{
if( input.value!='' ){
path=poly.getPath();
polypath=[];
for( let i=0; i < path.length; i++ ){
let point=path.getAt( i );
polypath.push( { lat:point.lat(), lng:point.lng() } )
}
let params={
path:JSON.stringify( polypath ),
name:input.value
}
let url=location.href;
let callback=function(r){
console.info( r );
input.value='';
poly.setMap( null );
createpoly();
};
/* send the polygon data */
ajax.call( this, url, params, callback );
}
})
}
</script>
<style>
body{ background:white; }
#container{
width: 90%;
min-height: 90vh;
height:auto;
box-sizing:border-box;
margin: auto;
float:none;
margin:1rem auto;
background:whitesmoke;
padding:1rem;
border:1px solid gray;
display:block;
}
#map {
width: 100%;
height: 80%;
clear:none;
display:block;
z-index:1!important;
background:white;
border:1px solid black;
}
</style>
</head>
<body>
<div id='container'>
<form method='post'>
<input type='text' name='polyname' />
<input type='button' value='Commit' title='Store the polygon' />
</form>
<div id='map'></div>
<div id='data'></div>
</div>
</body>
</html>
I'm using jQuery Nestable plugin with Codeigniter3 to create 5 levels of menus for website which a good solution for user can drab and drop to change the level and position of menus items. However my below function can create only first level of menus and when I change to sub level (2,3,4,5) of menu item it won't work for me.
Issue I could not change menus item to another level from level one. and I couldn't reversed menus item back to Parent if I've been changed it to be a children of any parent. Whatever Jquery Nestable is working very will.
This below function is using to update menus item to database which depend on
Menus column like :id, Parent_id, m_order.
This function will check up inside of $List array by foreach and array_key_exists as below description:
get array data from form using $this->get_child($this->input->post('list'));
Using Foreach and array_key_exists function to check any childrent of $List array and if it found any children it will update to database as below CI function.
And This if ($parent_id != $item['id']) {...} will not update parent_id for current id of parent.
public function savelist() {
if ($this->input->post('list')) {
$this->do_update($this->input->post('list'));
}
}
public function do_update($list, $parent_id = 0, &$m_order = 0) {
foreach ($list as $item) {
$m_order++;
$data = array(
'parent_id' => $parent_id,
'm_order' => $m_order,
);
if ($parent_id != $item['id']) {
$where = array('id' => $item['id']);
var_dump($data . ':' . $where);
$this->db->where($where);
$this->db->update('nav', $data);
}
if (array_key_exists("children", $item)) {
$this->do_update($item["children"], $item["id"], $m_order);
}
}
}
This Jquery Nestable Plugin and Ajax function is using to send any form data to server.
<script>
$(document).ready(function () {
var updateOutput = function (e) {
var list = e.length ? e : $(e.target), output = list.data('output');
$.ajax({
method: "POST",
url: "savelist",
data: {
list: list.nestable('serialize')
}, success: function (data) { //, textStatus, jqXHR
console.log(list.nestable('serialize'));
}
}).fail(function (jqXHR, textStatus, errorThrown) {
alert(" Unable to save new list order: " + errorThrown);
});
};
$('#nestable').nestable({
group: 1,
maxDepth: 7,
}).on('change', updateOutput);
});
</script>
How ever I've already create only one table to store all the menus item. and I make a conditional in PHP to check up Parent and Children when Menus id equal to Parent_id
Here is my table structure
CREATE TABLE IF NOT EXISTS `nav` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`uid` int(10) NOT NULL,
`text` varchar(500) NOT NULL,
`link` text NOT NULL,
`show_condition` int(5) NOT NULL,
`parent_id` int(5) NOT NULL,
`m_order` int(9) NOT NULL,
`class` varchar(50) NOT NULL,
`data` varchar(50) NOT NULL,
`des` text NOT NULL,
`lang` varchar(50) NOT NULL,
`accord` int(3) NOT NULL,
`footer` int(3) NOT NULL,
`f_sta` int(3) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=9 ;
The finally I got the menus editor as below image which let me change only one level os menus.
I have the same requirement like yours and workout with that take a look on my code which is almost same as yours,
Here is my Controller:
public function select_menu_priority() {
$data['product'] = $this->menu_model->select_menu_priority();
$data['li'] = $this->generate_li($data['product']);
$this->load->view("set_menu_priority_table", $data);
}
function generate_li($product,$parent = NULL){
$li = "";
$p1 = array_filter($product, function($a)use($parent){ return $a['parent_menu_id'] == $parent; });
foreach ($p1 as $p){
$inner_li = "";
$p2 = array_filter($product,function($a)use($p){ return $a['parent_menu_id'] == $p['id']; });
if($p2){
$inner_li = $this->generate_li($product,$p['id']);
}
$li .= "<li class='dd-item' data-id='".$p['id']."'><div class='dd-handle'>".$p['title']."</div>".$inner_li."</li>";
}
$ol = "<ol class='dd-list'>".$li."</ol>";
return $ol;
}
View set_menu_priority_table.php:
<?php
if (isset($product)) {
$entity = $this->input->post("entity");
$entity = $entity['id'];
if (count($product) > 0) {
?>
<div class="row-fluid" style="margin-bottom: 10px;">
<button class="btn btn-success btn-sm" tabindex="4" id="save">
<i class="fa fa-check"></i> Save
</button>
<p class="pull-right" style="margin-bottom: 10px;"><?php if ($entity == "product") { ?>Go to Category Priority<?php } ?><span class="label label-info ">Drag Menu to set Priority.</span></p>
<div class="clear"></div>
</div>
<div class="dd" id="product_list">
<input type="hidden" id="entity_type" name="entity" value="<?php echo $entity ?>" />
<?php echo $li; ?>
</div>
<?php } else { ?>
<p><span class="label label-warning">No <?php echo ($entity == "product") ? "product" : "category"; ?> found.</span><?php if ($entity == "product") { ?>Go to Category Priority<?php } ?></p>
<?php
}
} else {
?>
<p class="label label-info">Please select Category to Set Priority within the Category.</p>
<?php } ?>
<script type="text/javascript">
$("#save").off("click").on("click", function() {
var product_data = $("#product_list").nestable("serialize");
var data = {product_data: product_data, entity: $("#entity_type").val()};
if ($.bbq.getState("product_category") !== undefined) {
data['product_category'] = $.bbq.getState("product_category");
}
ajax_call({
url: '<?php echo site_url("admin/menu/update_menu_priority");?>',
type: "post",
dataType: "json",
data: data,
beforeSend: function() { },
success: function(result) {
if (result['status'] == "success") {
alert("Priority Updated!");
}
});
});
</script>
For Update That Priority Add function update_menu_priority in Controller:
public function update_menu_priority() {
$data = $this->input->post("product_data");
if (count($data)) {
$update = $this->menu_model->update_priority_data($data);
if ($update) {
$result['status'] = "success";
} else {
$result['status'] = "error";
}
} else {
$result['status'] = "error";
}
echo json_encode($result);
}
And at last ad model function for that update_priority_data:
function update_priority_data($data, $parent = NULL) {
$i = 1;
foreach ($data as $d) {
if (array_key_exists("children", $d)) {
$this->update_priority_data($d['children'], $d['id']);
}
$update_array = array("priority" => $i, "parent_menu_id" => $parent);
$update = $this->db->where("id", $d['id'])->update("menu", $update_array);
$i++;
}
return $update;
}
I hope this would be help full to you,
thanks.
i have following code for get data from database and sort draggable list using jquery ui elements.
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<style>
#sortable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#sortable li { margin: 0 3px 3px 3px; padding: 0.4em; padding-left: 1.5em; font-size: 1.4em; height: 18px; background-color:#CCC;}
#sortable li span { position: absolute; margin-left: -1.3em; }
</style>
<script>
$(function() {
$( "#sortable" ).sortable();
$( "#sortable" ).disableSelection();
});
</script>
<?php
$con=mysqli_connect("localhost","root","","db_name");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$user_id = $_SESSION['user_id'];
$result = mysqli_query($con,"SELECT * FROM users WHERE user_id = '$user_id'");
echo "<ul id='sortable'>";
while($row = mysqli_fetch_array($result))
{
echo "<li class='ui-state-default'>" . $row['Name'] . ' ' . $row['UserName'] . $row['sort'] ."</li>";
}
echo "</ul>";
mysqli_close($con);
?>
This is my database table structure
Table Name = users
Columns = user_id, Name, UserName, Password, sort
Example Results
user_id Name UserName Password sort
1 AAA aa *** 1
2 BBB bb *** 2
3 CCC cc *** 3
4 DDD dd *** 4
what i am asking is, i can Reorder list items by using jquery draggable properties, but how can i save sort number to database if reordered list items.?
jQuery UI sortable has a stop callback which is called when you stop moving a sortable. It also has a serialize function that you can use in combination to send the order of your sortables to your to the process which updates your database. You can use it like this:
To use serialize you need to amend your sortable element in the DOM so that it contains a reference to the user_id. E.g.
<li class="ui-state-default" id="id_<?php echo $row['user_id'] ?>">...</li>
Then when you serialize the sortable, it will build a list of parameters. You don't have to use the id attribute to reference your data, read more about the serialize method here. But below is an example of how you can do it using the id attribute
var $sortable = $( "#sortable" );
$sortable.sortable({
stop: function ( event, ui ) {
// parameters will be a string "id[]=1&id[]=3&id[]=10"...etc
var parameters = $sortable.sortable( "serialize" );
// send new sort data to process
$.post("/sort/my/data.php?"+parameters);
}
});
You then need a process that receives this data and updates the database. I'll leave most of this up to you, but here's a minimal example.
<?php
// Store user IDs in array. E.g. array(0 => "1", 1 => "3", 2 => "10"....)
$userIds = $_POST['id'];
// Connect to your database
$conn = mysqli_connect("localhost","root","","db_name");
foreach ($userIds as $key => $userId) {
$sequence = $key + 1;
$stmt = $conn->prepare("UPDATE users SET sort = $sequence WHERE user_id = ?");
$stmt->bind_param("i", (int) $userId);
$stmt->execute();
}
$stmt->close();
Hi this question relates to a recent question I had posted that I'm trying to find at least some help with in general that leads to solve the entire problem.
The following code is not mine and I had to fix it just to get it working to the extent it is now but the problem the algorithm within _get_chat_messages continues to execute the else condition. This doesn't make sense because there's chat message data in Mysql. I'm trying to make this source code work hoping it will lead me in the right direction with refreshing chat message content automatically without forcing browser client refreshes or redirecting headers.
What's causing _get_chat_messages to execute the else condition disregarding the if condition. The if conditions seems to evaluate to TRUE which doesn't make sense.
Any help much appreciated. Thanks.
//JQUERY/AJAX:
$(document).ready(function() {
setInterval(function() { get_chat_messages(); } , 2500);
$("input#chat_message").keypress(function(e) {
if (e.which == 13) {
$("a#submit_message").click();
return false;
}
});
$("#submit_message").click(function() {
var chat_message_content = $("input#chat_message").val();
//this if condition seems to be ignored not sure why?
if (chat_message_content == "") { return false; }
$.post(base_url + "chat/ajax_add_chat_message", { chat_message_content : chat_message_content, chat_id : chat_id, user_id : user_id }, function(data) {
if (data.status == 'ok')
{
var current_content = $("div#chat_viewport").html();
$("div#chat_viewport").html(current_content + data.message_content);
}
else
{
// there was an error do something
}
}, "json");
$("input#chat_message").val("");
return false;
});
function get_chat_messages()
{
$.post(base_url + "chat/ajax_get_chat_messages", { chat_id : chat_id }, function(data) {
if (data.status == 'ok')
{
var current_content = $("div#chat_viewport").html();
$("div#chat_viewport").html(current_content + data.message_content);
}
else
{
// there was an error do something
}
}, "json");
}
get_chat_messages();
});
//CONTROLLER:
class Chat extends CI_Controller {
public function __construct()
{
parent:: __construct();
$this->load->model('chat_model');
}
public function index()
{
/* send in chat id and user id */
$this->view_data['chat_id'] = 1;
// check they are logged in
if (! $this->session->userdata('logged_in')) {
redirect('user/login');
}
$this->view_data['user_id'] = $this->session->userdata('user_id');
$this->session->set_userdata('last_chat_message_id_' . $this->view_data['chat_id'], 0);
$this->view_data['page_title'] = 'web based chat app :)';
$this->view_data['page_content'] = 'view_chat';
$this->load->view('view_main', $this->view_data);
}
public function ajax_add_chat_message()
{
/* Scalar Variable data that needs to be POST'ed to this function
*
* chat_id
* user_id
* chat_message_content
* *
*/
$chat_id = $this->input->post('chat_id');
$user_id = $this->input->post('user_id');
$chat_message_content = $this->input->post('chat_message', TRUE);
$this->chat_model->add_chat_message($chat_id, $user_id, $chat_message_content);
// grab and return all messages
$this->ajax_get_chat_messages($chat_id);
}
public function ajax_get_chat_messages($chat_id)
{
$chat_id = $this->input->post('chat_id');
echo $this->_get_chat_messages($chat_id);
}
private function _get_chat_messages($chat_id)
{
$last_chat_message_id = (int)$this->session->userdata('last_chat_message_id_' . $chat_id);
$chat_messages = $this->chat_model->get_chat_messages($chat_id, $last_chat_message_id);
if ($chat_messages->num_rows() > 0)
{
// store the last chat message id
$last_chat_message_id = $chat_messages->row($chat_messages->num_rows() - 1)->chat_message_id;
$this->session->set_userdata('last_chat_message_id_' . $chat_id, $last_chat_message_id);
// we have some chat let's return it
$chat_messages_html = '<ul>';
foreach ($chat_messages->result() as $chat_message)
{
$li_class = ($this->session->userdata('user_id') == $chat_message->user_id) ? 'class="by_current_user"' : '';
$chat_messages_html .= '<li ' . $li_class . '>' . '<span class="chat_message_header">' . $chat_message->chat_message_timestamp . ' by ' . $chat_message->name . '</span><p class="message_content">' . $chat_message->chat_message_content . '</p></li>';
}
$chat_messages_html .= '</ul>';
$result = array('status' => 'ok', 'content' => $chat_messages_html);
//header('Content-Type: application/json',true);
return json_encode($result);
exit();
}
else
{
// we have no chat yet
$result = array('status' => 'no chat', 'content' => '');
//header('Content-Type: application/json',true);
return json_encode($result);
exit();
}
}
}
//MODEL:
class chat_model extends CI_Model {
public function __construct()
{
parent::__construct();
}
public function add_chat_message($chat_id, $user_id, $chat_message_content)
{
$query_str = "INSERT INTO chat_messages (chat_id, user_id, chat_message_content) VALUES (?, ?, ?)";
$this->db->query($query_str, array($chat_id, $user_id, $chat_message_content));
}
public function get_chat_messages($chat_id, $last_chat_message_id = 0)
{
$query_str = "SELECT
cm.chat_message_id,
cm.user_id,
cm.chat_message_content,
DATE_FORMAT(cm.create_date, '%D of %M %Y at %H:%i:%s') AS chat_message_timestamp,
u.name
FROM chat_messages cm
JOIN users u ON cm.user_id = u.user_id
WHERE cm.chat_id = ?
and cm.chat_message_id > ?
ORDER BY cm.chat_message_id ASC";
$result = $this->db->query($query_str, array($chat_id, $last_chat_message_id));
return $result;
}
}
//VIEW FILE HENCE VIEW_CHAT.PHP
<html>
<head>
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="<?php echo base_url() . 'public/';?>chat.js">
</script>
<script type="text/javascript">
var base_url = "<?php echo base_url();?>";
var chat_id = "<?php echo $chat_id; ?>";
var user_id = "<?php echo $user_id; ?>";
</script>
</head>
<body>
<style type="text/css">
div#chat_viewport {
font-family:Verdana, Arial, sans-serif;
padding:5px;
border-top:2px dashed #585858;
min-height:300px;
color:black;
max-height:650px;
overflow:auto;
margin-bottom:10px;
width:750px;
}
div#chat_viewport ul {
list-style-type:none;
padding-left:10px;
}
div#chat_viewport ul li {
margin-top:10px;
width:85%;
}
span.chat_message_header {
font-size:0.7em;
font-family:"MS Trebuchet", Arial, sans-serif;
color:#547980;
}
p.message_content {
margin-top:0px;
margin-bottom:5px;
padding-left:10px;
margin-right:0px;
}
input#chat_message {
margin-top:5px;
border:1px solid #585858;
width:70%;
font-size:1.2em;
margin-right:10px;
}
input#submit_message {
font-size:2em;
padding:5px 10px;
vertical-align:top;
margin-top:5px;
}
div#chat_input { margin-bottom:10px; }
div#chat_viewport ul li.by_current_user span.chat_message_header {
color:#e9561b;
}
</style>
<h1>Let's do some chatting :D</h1>
<div id="chat_viewport">
</div>
<div id="chat_input">
<?php echo form_open('chat/ajax_add_chat_message'); ?>
<input id="chat_message" name="chat_message" type="text" value="" tabindex="1" />
<?php echo form_submit('submit_message','submit_message'); ?>
<?php echo anchor('#', 'Say it', array('title' => 'Send this chat message', 'id' => 'submit_message'));?>
<div class="clearer"></div>
<?php echo form_close(); ?>
</div>
</body>
</html>
I am not sure but I have a feeling that the json that you receive from the server is not formatted properly. See this: jQuery won't parse my JSON from AJAX query