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();
Related
1st time asking here!
I have a MySQL SELECT query and array of results. I have a container and within that container I want to display child div(s) displaying the array result + JQuery to add some nice fadeIn and fadeOut. The issue is the script display some of the array but NEVER all. I have 7 but the page shows 5 sometimes even 2 only and the data seems to be picked randomly.
// Fetch user notifications
$stmt0 = $conn->prepare("SELECT notifid, notification FROM notifications WHERE userid = :userid AND username = :uname;");
$stmt0->execute(['userid' => $userid, 'uname' => $username]);
$results0 = $stmt0->fetchAll();
foreach ($results0 as $row0) {
$notifid = $row0['notifid'];
$notification = $row0['notification'];
$notificationid = substr(sha1(mt_rand()), 0, 8);
echo "<div class='bluenot' id='".$notificationid."'>✔ <b><i>$notification</i></b></div>";
echo '<script>
$(document).ready(function(){
var notifid = ' . $notificationid . ';
$("#notifybox").append($ (notifid) );
setTimeout(function() {
$(notifid).fadeIn("fast", function () { $(this).delay(5000).fadeOut("fast"); });
$(notifid).css("display", "block");});
});
</script>';
CSS :
.notifybox {
width: auto;
height: auto;
position: fixed;
bottom: 0;
left: 15px;
z-index: 1000 important;
}
.bluenot {
width: 400px;
height: 80px;
padding: 20px 40px 20px 40px;
margin-top: 8px;
margin-bottom: 8px;
display: none;
background: #aaa9ff;
border-left: #2933aa 10px solid;
border-radius: 10px;
color: #353759;
text-align: center;
}
SOLVED:
Made a copy of class .bluenot and named it .dbnot then changed the code to :
echo "<div class='dbnot' id='".$notificationid."'>✔ <b><i>$notification</i></b></div>";
echo '<script>
$("#notifybox").append($ (".dbnot") );
$(".dbnot").fadeIn( 800 ).delay( 1000 ).fadeOut( 400 ).$(".dbnot").css("display", "block");
</script>';
Hope this helps anyone who would face the same issue.
You are missing the closing curly brackets for your foreach loop but assuming you have it after your <script> block then i would guess you are over writing the variable "notifid"
I would try to rearrange your logic and if you are deadset on this approach then create the variable "notifid" with a another variable to avoid duplicate declarations
something maybe like
$(document).ready(function(){
var notifid_' . $notificationid . ' = ' . $notificationid . ';
$("#notifybox").append($ (notifid_' . $notificationid . ') );
setTimeout(function() {
$(notifid_' . $notificationid . ').fadeIn("fast", function () { $(this).delay(5000).fadeOut("fast"); });
$(notifid_' . $notificationid . ').css("display", "block");});
});
I am trying to make orgchart in my code, a have not any idea about this chart. I want to make a a tree like chart, and want data from mysql table.
Table is : treechart
id name treeid
1 a 1
2 aa 11
3 aaa 111
4 aaaa 1111
5 ab 12
6 aba 121
7 abb 122
8 ac 13
My code is as below :
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {packages:["orgchart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('string', 'Manager');
data.addColumn('string', 'ToolTip');
// For each orgchart box, provide the name, manager, and tooltip to show.
<?php
include get_template_directory()."/connect/connect.php";
$result = mysql_query("select * from treechart order by id asc");
$members = array();
$demo = "[\n";
while ($row = mysql_fetch_array($result))
{
$members[$row[2]] = $row[1];
}
function search_tree($searchkey)
{
return $members[$searchkey];
}
foreach($members as $key=>$member)
{
if(strlen($key)==1)
{
$demo = $demo."['".$member."','','".$member."'],\n";
$one = $member;
}
if(strlen($key)==2)
{
$demo = $demo."['".$member."','".$one."',''],\n";
}
if(substr($key,0,2)=="11")
{
if(strlen($key)==3)
{
$newkey = search_tree("11");
echo $newkey."---.";
}
}
$oldkey = strlen($key);
}
$demo = substr($demo,0,strlen($demo)-2);
$demo = $demo."]";
print_r($newdemo);
?>
data.addRows(<?php echo $demo; ?>);
// Create the chart.
var chart = new google.visualization.OrgChart(document.getElementById('chart_div'));
// Draw the chart, setting the allowHtml option to true for the tooltips.
chart.draw(data, {allowHtml:true});
}
</script>
</head>
<body>
<div id="chart_div"></div>
</body>
</html>
My problem is in $newkey I can't any value, I want the value of 11,12,13 keys value in $newkey. And I have very big amount of data in table, so if anyone have any short coding idea, then help me in my code.
You have to define parent column in your table
id | parrentId | Name
Here is an example
var orgchart = new getOrgChart(document.getElementById("people"),{
dataSource: [
{ id: 1, parentId: null, Name: "1"},
{ id: 2, parentId: 1, Name: "2"},
{ id: 3, parentId: 1, Name: "3"}]
});
html,
body {
margin: 0px;
padding: 0px;
height: 100%;
overflow: hidden;
}
#people {
width: 100%;
height: 100%;
}
<link href="http://www.getorgchart.com/GetOrgChart/getorgchart/getorgchart.css" rel="stylesheet"/>
<script src="http://www.getorgchart.com/GetOrgChart/getorgchart/getorgchart.js"></script>
<div id="people"></div>
I am working with a school project. The basic ide of the project is, that we have some arduino boxes the sends some sensor data to a mysql db and we have a website that display it. Sensor data is sending lets say every 6sec.
I don´t have a lot of experience with PHP. But i am tinkerin my way, learing step by step..cowboy style? =)
The html/ajax/css:
<!DOCTYPE html>
<html>
<head>
<title>Arduino event poller</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<style type = "text/css" media="screen">
body{ font:13px/1.5 "helvetica neue", helvetica, arial, san-serif; background:#FFF; }
#main{ width:430px; height: 300px; display:block; padding:10px 0; float: left; overflow: auto;}
.event { display:block; background: #ececec; width:380px; padding:10px; margin:10px; overflow:hidden; text-align: left; }
.event img { display:block; float:left; margin-right:10px; }
.event p { font-weight: bold; }
.event img + p { display:inline; }
.patient-name { display:inline; color: #999999; font-size: 9px; line-height:inherit; padding-left: 5px; }
.event-text{ color: #999999; font-size: 12px; padding-left: 5px; }
.event-timestamp{ color: #000; padding-left: 5px; font-size: 9px;}
</style>
<script type="text/javascript" charset="utf-8">
var timeStamp = null;
/* Simple helper to add some divs.*/
function addevents(patientroom, patientname, eventtyp, timestamp)
{
$("#main").append(
"<div class='event'>"
"<p>" + patientroom + "</p>"
"<p class='patient-name'>" + patientname + "</p>"
"<p class='event-text'>" + eventtyp + "</p>"
"<p class='event-timestamp'>" + timestamp + "</p>"
"</div>"
);
}
/*This requests the url "getevents.php" When it complete*/
function waitForEvents()
{
$.ajax({
type: "GET",
url: "getevents.php?timeStamp=" + timeStamp,
async: true, /* If set to non-async, browser shows page as "Loading.."*/
cache: false,
timeout:50000, /* Timeout in ms */
success: function(data, textStatus, jqXHR) /* called when request to getevents.php completes */
{
addevents(data.patientroom, data.patientname, data.eventtyp, data.timestamp);
setTimeout(
waitForEvents, /* Request next event */
1000 /* ..after 1 seconds */
);
},
error: function (XMLHttpRequest, textStatus, errorThrown){
alert("Error:" + textStatus + " (" + errorThrown + ")");
setTimeout(
'waitForEvents()', /* Try again after.. */
"5000"); /* milliseconds (5seconds) */
},
});
};
$(document).ready(function(){
waitForEvents(); /* Start the inital request */
});
</script>
</head>
<body>
<div id="main">
</div>
</body>
</html>
My backend php:
<?php
function getEvents()
{
$con = mysql_connect("localhost","***","***");
if(!con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("arduino_db",$con);
$result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1");
if($result)
{
$patientroom = $row['rumNr'];
$patientname = $row['inneboendeNamn'];
$eventtyp = $row['handelse'];
$timestamp = $row['timestamp'];
}
if($row)
{
header('application/json');
echo json_encode($row);
exit;
}
$lastmodif = isset($_GET['timeStamp']) ? $_GET['timeStamp'] : 0;
$currentmodif = filemtime($result);
while($currentmodif <= $lastmodif)
{
unsleepp(1000);
clearstatcache();
$currentmodif = filemtime($result);
}
}
?>
My question:
How to I fetch each row from the db and return each row in JSON format to the method "waitForEvents" in the frontend.
The example doesn't have to be scaleable, secure or complete, it just needs to work =)
UPDATE: new code based on Johns tips. All I gets is a blank page, and no errors.
The first thing that popped out to me is that your MySQL call is sort of blown.
When you run this line:
$result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1");
You're going to get a MySQL resource. You need to utilize that to get your row:
$result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1");
if ($result)
{
$row = mysql_fetch_assoc($result);
if ($row)
{
// Your result is here, as a big associative array. Each column in your
// table is now keyed to this array. Exact fields will depend on your DB.
//
// Just access it like something like this:
$id = $row['id'];
$time = $row['time_stamp'];
}
}
to echo it back out as JSON:
... // snip
if ($row)
{
header('application/json');
echo json_encode($row);
exit;
}
}
// handle your errors!
added: Additional error found in OP question:
// The following line isn't valid. This isn't what you'll get back from $.ajax.
// success: function(patientroom, patientname, eventtyp, timestamp)
// Corrected code:
success: function(data, textStatus, jqXHR)
/* called when request to getevents.php completes */
{
addevents(data.patientroom, data.patientname, data.eventtyp, data.timestamp);
setTimeout(
waitForEvents, /* Request next event */
1000 /* ..after 1 seconds */
);
},
Further updates. You mixed & matched the code from above.
$result = mysql_query("SELECT * FROM events ORDER BY eventID DESC LIMIT 1");
if($result)
{
// this has to go inside of this check. This is where you *ASSIGN* $row.
$row = mysql_fetch_assoc($result);
// You need to rekey $row before you output:
$retVal = array('patientroom'=>$row['rumNr'],
'patientname'=>$row['inneboendeNamn'],
'eventtyp'=>$row['handelse'],
'timestamp'=>$row['timestamp']);
// I'm not sure what you're doing with the incoming timestamp. Should we just
// return it back out?
$retVal['ajax_timestamp'] = $_GET['timeStamp'];
header('application/json');
echo json_encode($retVal);
exit; // this exits. Comment this out if you want, but don't try to write anything else out to the buffer.
}
// Not sure what you're trying to do here. I'll comment out for now.
/*
$lastmodif = isset($_GET['timeStamp']) ? $_GET['timeStamp'] : 0;
$currentmodif = filemtime($result);
while($currentmodif <= $lastmodif)
{
unsleepp(1000);
clearstatcache();
$currentmodif = filemtime($result);
}
*/
}
I understand know that you shouldnt do long-polling with php. It's to messy if you aint a pro php-hacker and for many other reasons like:
PHP is made for fast execution (not for waiting)
PHP will force you to do some kind of polling on the server side and relying on sleep()
PHP will eat your RAM while so are spawning processes for each requests (Apache will do so)
The thing I need for my project is to show new data without refreshing the hole site. I did it like this:
<script type="text/javascript">
var timeoutId;
var intervalId;
function doIt(){
$("#main").load("refresh.php");
}
$(document).ready(function(){
timeoutId = setTimeout(function(){
doIt();
intervalId = setInterval(function(){
doIt();
}, 5000); //Request the doIt() method every 5ms.
}, 3000); //Delay calculated on the server to trigger the function at the appropriate time
});
</script>
I have this friend request page, and i want my div
echo "<div style=' font-weight: bold; background: #283b43; border-bottom: 1px dashed #719dab;'>";
echo "<img src='images/NewFriend_small.png' style='float: left; margin-left: 25px; margin-right: 10px;'>";
echo "Friend requests";
echo "</div>";
To disappear too if it's the last friend request the user have.
Right now it doesnt do it, and only slide up the actual request (username, picture and so)
How should i check for if its the last friendrequest?
Right now its my code is like this
$friendsWaiting = mysql_query("SELECT * FROM users_friends where uID = '$v[id]' AND type = 'friend' AND accepted = '0'");
while($showW = mysql_fetch_array($friendsWaiting)){
echo "id: $showU[bID]";
}
JS when they accept/deny friend:
function MeYouFriendNB(confirm){
var c = confirm ? 'confirm' : 'ignore';
var fID = $('#fID').val();
$.ajax({
type: "POST",
url: "misc/AddFriend.php",
data: {
mode: 'ajax',
friend: c,
uID : $('#uID').val(),
fID : $('#fID').val(),
bID : $('#bID').val()
},
success: function(msg){
$('#friend'+fID).slideUp('slow');
$('#Friendlist').prepend(msg);
$('#theNewFriend').slideDown('slow');
}
});
}
Use the :last selector in jQuery
http://api.jquery.com/last-selector/
$('div.friend:last').slideUp();
Is that what you were looking for?
I'm creating my own recipe box using php/mysql and one part I'm stuck on is actually creating the recipes, specifically selecting the ingredients.
What I wanted to do instead is have a auto-complete search box where I can type out names of the ingredients, have the results drop down right below, and click the ones I'm looking for. After clicking the ingredient, it'll be listed below the search box with an input to put quantity and an "x" to delete if needed. This of course would grow depending on how many ingredients the recipe requires. At the end, I would just take the data and do an insert into my database.
I've seen a lot of AJAX tutorials on getting the auto-complete search box functionality, but nothing tying it to the value selection. The best example of what I'm going for can be found at http://supercook.com. They have it so you can search for recipes.
Any suggestions or online resources?
Thanks!
you asked a great question. Below I've written a short example to get you started. Just save it as ingredients.php and it should work. Of course, you'll need to add your database connection and query to give it real data. I've used the jQuery library because it makes the Javascript part a lot easier.
<?php
// connect to database here
if (isset($_POST['q'])) {
if (trim($_POST['q']) === '') die('[]');
// $q = mysql_real_escape_string($_POST['q']);
// run a query like: "SELECT id, name FROM ingredients WHERE name LIKE '{$q}%'"
// and put the result in the $result array.
// This is sample data:
$result = array(
array('id' => 71, 'name' => 'apple'),
array('id' => 3, 'name' => 'anchovies'),
array('id' => 230, 'name' => 'artichoke'),
);
if (function_exists('json_encode')) die(json_encode($result));
else {
$escaped = array();
foreach ($result as $r) $escaped[] = str_replace(array('\\', '"'), array('\\\\', '\"'), $r);
die('["'.join('","', $escaped).'"]');
}
}
$data = array();
if (isset($_POST['ingredients'])) {
foreach ($_POST['ingredients'] as $i => $ingredient) {
$data[] = array(
'ingredient' => $ingredient,
'quantity' => $_POST['quantities'][$i],
);
}
// save data to the database here (or inside the foreach loop above)
}
?>
<html><head></head><body>
<style>
#wrap { position: relative }
#pop {
position: absolute;
border: 1px solid black;
background-color: white;
display: none;
}
</style>
<?php if (count($data)): ?>
<h3>Saved:</h3>
<pre><?php print_r($data) ?></pre>
<?php endif; ?>
<div id="wrap">
<input id="adder" />
<div id="pop"></div>
</div>
<form method="post">
Ingredients:<br />
<div id="recipe"></div>
<input type="submit" value="Save" />
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
var last_query = '';
jQuery(function() {
jQuery('#adder').val('').keyup(function() {
var query = jQuery(this).val();
if (query != last_query) jQuery.post('ingredients.php', {q: query}, function(data) {
var p = jQuery('#pop').html('').show();
for (var i=0; i<data.length; i++) {
p.append(jQuery('<p>'+data[i].name+'</p>').bind('click', { ingredient: data[i] }, function(e) {
add_ingredient(e.data.ingredient);
jQuery('#pop').hide();
jQuery('#adder').val('');
}));
}
}, 'json');
else jQuery('#pop').show();
last_query = query;
});
});
function add_ingredient(data) {
console.log(data);
var ingredient = jQuery('<div> <input name="quantities[]" size="2" /> '+data.name
+ '<input type="hidden" name="ingredients[]" value="'+data.id+'" /></div>');
var remover = jQuery('<span>X</span>').click(function() {
jQuery(this).parent().remove();
});
jQuery('#recipe').append(ingredient.prepend(remover));
}
</script>
</body></html>