Sortable Portlet Update Query - php

I am attempting to update some sortable divs that are connected with connectwith. I have done a single table before and the update query works, but when mutiple divs are involved it gets tricky. The problem is I have a field in the database called div that needs to update as well with whatever div the sortable object is getting dropped into AS WELL AS put it in a specific order within that div.
EDIT: SOOO, how can I create a sortable update query for multiple div.id locations?
The results I am getting from the code work for just updating the order inside one div, but across multiple divs there is no update. Plus, I'm not exactly sure of the easiest way to find the div I moved the content to and save that to the database.
Okay, so here's the code I have so far for just updating the order within one div:
$(".heriyah").sortable({
handle : '.handle',
connectWith: ".heriyah",
revert: "invalid",
update : function () {
var order = $('.heriyah').sortable('serialize');
$("#info").load("admin/sortable.php?"+order);
}
});
And the PHP:
foreach ($_GET['listItem'] as $position => $item) :
$sql[] = "UPDATE `temp` SET `order` = $position WHERE `id` = $item";
endforeach;
print_r ($sql);
And the HTML/PHP to produce the content (using alot of PHP and JQuery):
<script type="text/javascript">
(function() {
$('div.heriyah').each(function() {
$(this).html('<div class="add"><div id="add_button_container"><div id="add_button" class="edit_links">+ ADD NEW CONTENT</div></div></div><div class="clear"></div><div class="placeable" style="height:20px;background-color:#fff;"></div></div>');
var curID = $(this).attr('id');//get the id before you go into fallr
$('.add').click(function() {
$.fallr('show', {
content : '<iframe width="620" height="600" src="<? echo $URL ?>/manage_content.php?pageID=<? echo $pageID; ?>&div='+ curID +'"></iframe>',
width : 620 + 5, // 100 = for width padding
height : 600,
closeKey : true,
closeOverlay : true,
buttons : {}
});
});
});
})();
<?
include_once('system/js/dbc.php');
$pageID = $_REQUEST['pageID'];
$getdiv2 = mysql_query("SELECT * FROM temp WHERE pageID = '$pageID' ORDER BY `order` ASC");
while ($row = mysql_fetch_assoc($getdiv2))
{
echo "$('#{$row['div']}.heriyah').append('<div class=sortable id=listItem_{$row['id']}><div id=heriyah_content class=sortable_header>{$row['title']}<br>{$row['maintext']}<div id=heriyah_handle class=handle></div><a onClick=edit_{$row['id']}();return false><div id=heriyah_content_hover></div></a></div></div>');\n";
}
?>
</script>
<script>
$(".heriyah").sortable({
handle : '.handle',
connectWith: ".heriyah",
revert: "invalid",
update : function () {
var order = $('.heriyah').sortable('serialize');
$("#info").load("admin/sortable.php?"+order);
}
});
</script>
<div id="info"></div>

I have produced something based on the jQuery UI connect-lists example.
I have not implemented the backend calling or database side components but I'm sure you can work that out. I am only interested in capturing what has moved and to where.
The receive event is triggered when you drag items between lists so we can use that.
We also need to catch the update event but are not interested in items that are already being dealt with by the receive event. To do this we need to check to see if ui.sender is undefined (as it will be for all non-connected list transfers). However it seems that the update event calls all the sortable containers when the update has completed. We only want to capture the data when the updated item's parent is the same as the list receiving the update event trigger. (I hope that makes sense!)
In summary the receive event will be used to capture all the inter connect-list transfers and the update event will capture any sorting that happens within an element list.
<!DOCTYPE html>
<html lang="en">
<head>
<base href="http://jqueryui.com/demos/sortable/"/>
<meta charset="utf-8">
<title>jQuery UI Sortable - Connect lists</title>
<link rel="stylesheet" href="../../themes/base/jquery.ui.all.css">
<script src="../../jquery-1.6.2.js"></script>
<script src="../../ui/jquery.ui.core.js"></script>
<script src="../../ui/jquery.ui.widget.js"></script>
<script src="../../ui/jquery.ui.mouse.js"></script>
<script src="../../ui/jquery.ui.sortable.js"></script>
<link rel="stylesheet" href="../demos.css">
<style>
#sortable1, #sortable2, #sortable3 { list-style-type: none; margin: 0; padding: 0; float: left; margin-right: 10px; }
#sortable1 li, #sortable2 li, #sortable3 li { margin: 0 5px 5px 5px; padding: 5px; font-size: 1.2em; width: 120px; }
</style>
<script>
$(function() {
$( "#sortable1, #sortable2, #sortable3" ).sortable({
connectWith: ".connectedSortable",
update: function(event, ui){
if(($(ui.sender).attr('id') == undefined)&&($(this).attr('id') == ui.item.parent().attr('id'))){
alert('UPDATE ' + $(this).attr('id') + ' ' + (ui.item.index()+1) + ' ' + $(ui.item).text());
}
},
receive: function(event, ui){
alert('RECEIVE: ' + $(ui.sender).attr('id') + '=>' + $(this).attr('id') + ' ' + (ui.item.index()+1) + ' ' + $(ui.item).text());
}
}).disableSelection();
});
</script>
</head>
<body>
<div class="demo">
<ul id="sortable1" class="connectedSortable">
<li class="ui-state-default">A</li>
<li class="ui-state-default">B</li>
<li class="ui-state-default">C</li>
<li class="ui-state-default">D</li>
<li class="ui-state-default">E</li>
</ul>
<ul id="sortable2" class="connectedSortable">
<li class="ui-state-highlight">F</li>
<li class="ui-state-highlight">G</li>
<li class="ui-state-highlight">H</li>
<li class="ui-state-highlight">I</li>
<li class="ui-state-highlight">J</li>
</ul>
<ul id="sortable3" class="connectedSortable">
<li class="ui-state-default">K</li>
<li class="ui-state-default">L</li>
<li class="ui-state-default">M</li>
<li class="ui-state-default">N</li>
<li class="ui-state-default">O</li>
</ul>
</div>
</body>
</html>

Related

Make jQuery work with all numbered varients of ID [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
I'm coding something in-which certain text appears depending on which li you click. The jQuery I have written works, but doesn't take into account that all this data is being outputted by a PHP loop. Is there a way where I can change the jQuery I've written can work for an infinite number of li's rather than only the ones I've specified?
$('#selection1').on('click', function() {
$('.content-block').removeClass('active');
$('.content-selector').removeClass('active');
$('#message1').addClass('active');
$('#selection1').addClass('active');
});
$('#selection2').on('click', function() {
$('.content-block').removeClass('active');
$('.content-selector').removeClass('active');
$('#message2').addClass('active');
$('#selection2').addClass('active');
});
$('#selection3').on('click', function() {
$('.content-block').removeClass('active');
$('.content-selector').removeClass('active');
$('#message3').addClass('active');
$('#selection3').addClass('active');
});
Remember that in jQuery you use selectors from css, so the easiest way to do it would be to cahnge this
$('#selection1').on('click', function() {
to this
$('[id^="selection"]').on('click', function() {
Which will apply to all elements that has an id that starts with "selection".
Also inside the click event use variable this instead of refering again to id.
$('[id^="selection"]').on('click', function() {
var selection = $(this),
number = selection.attr("id").substr(9);
$('.content-block, .content-selector').removeClass('active');
$('#message' + number).addClass('active');
selection.addClass('active');
});
If you make the buttons, you can add a data-atribute (1,2 or 3), and then add a class to the clicked button like this:
$('.buttonClicked').on('click', function() {
$('.content-block').removeClass('active');
$('.content-selector').removeClass('active');
var num = $(this).attr('data-atribute'); //Get the 1,2 or 3 number dynamically
$('#message'+num).addClass('active');
$('#selection'+num).addClass('active');
});
Use the function like this
$('li').on('click', function() {
var num = $(this).attr("id").substr(6);
console.log(num)
$('.content-block').removeClass('active');
$('.content-selector').removeClass('active');
$('#message'+ num).addClass('active');
$('#selection'+ num).addClass('active');
});
$('li').on('click', function() {
var num = $(this).attr("id").substr(6);
console.log(num)
$('.content-block').removeClass('active');
$('.content-selector').removeClass('active');
$('#message'+ num).addClass('active');
$('#selection'+ num).addClass('active');
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<ul>
<li id="select1">
1
</li>
<li id="select2">
2
</li>
<li id="select3">
3
</li>
<li id="select4">
4
</li>
</ul>
If you really don't want to change your HTML, you can use jQuery ^= selector to select every element with an id starting with "selection".
$(document).on('click', '[id^="selection"]', function() {
let id = +this.id.replace('selection',''); //Get the ID value here
$('.content-block,.content-selector').removeClass('active');
$('#message'+id).addClass('active');
$(this).addClass('active');
});
div{
width: 20px;
height: 20px;
background-color: blue;
display: inline-block;
margin: 5px;
}
div.active{
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="selection1"></div>
<div id="selection2"></div>
<div id="selection3"></div>
<div id="selection4"></div>
<div id="selection5"></div>
<div id="message1"></div>
<div id="message2"></div>
<div id="message3"></div>
<div id="message4"></div>
<div id="message5"></div>

JQuery 5 star rating system

I'm creating a 5 star rating system with html php and jquery i dont know how to stop the stars rating when user has clicked on rating.
In my code when user click on 4 stars the alert box shows 4 stars but when the user move his mouse from stars the stars shows 0 rating.
here is my code, i'm not posting the css here
HTML :
<div class="rating">
<div class="ratings_stars" data-rating="1"></div>
<div class="ratings_stars" data-rating="2"></div>
<div class="ratings_stars" data-rating="3"></div>
<div class="ratings_stars" data-rating="4"></div>
<div class="ratings_stars" data-rating="5"></div>
</div>
JQUERY :
$('.ratings_stars').hover(
// Handles the mouseover
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
// Handles the mouseout
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
}
);
$('.ratings_stars').click(function() {
$('.ratings_stars').removeClass('selected'); // Removes the selected class from all of them
$(this).addClass('selected'); // Adds the selected class to just the one you clicked
var rating = $(this).data('rating');
alert(rating);
// Get the rating from the selected star
$('#rating').val(rating); // Set the value of the hidden rating form element
});
Guessing because you haven't said what you expect to happen. It could be that you want the selected rating, and the stars before it, to be highlighted.
So instead of this
$(this).addClass('selected');
you use this, similar to how you have previously.
$(this).prevAll().andSelf().addClass('selected');
But I would also remove the hover class so that it's obvious to the user on click
$(this).prevAll().andSelf().addClass('selected').removeClass('ratings_over');
Demo
<!--SAVE AS WHATEVAUWANNA.HTML AND TEST-->
<html>
<head>
<title>Rating System jQuery Plug by Aldanis Vigo</title>
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js'></script>
<style type='text/css' language='css'>
.record{
opacity: .50;
}
#value-display{
position: relative;
top: -5px;
margin-left: 10px;
color: orange;
font-weight: bold;
}
</style>
</head>
<body>
<span value='0' id='ratingbar'>
<img class='record' number='1'/>
<img class='record' number='2'/>
<img class='record' number='3'/>
<img class='record' number='4'/>
<img class='record' number='5'/>
<span id='value-display'>0 / 5</span>
</span>
</body>
<script>
//Change these variables to your liking!!
var iconsrc = 'https://upload.wikimedia.org/wikipedia/commons/a/ae/Record2.png';
var iconwidth = '20px';
var iconheight = '20px';
var value = $('#ratingbar').attr('value');
$('#ratingbar img').each(function(){
//Set the icon for each
$(this).attr('src', iconsrc);
$(this).attr('width', iconwidth);
$(this).attr('height', iconheight);
$(this).hover( function(){
$(this).css('opacity','1');
$(this).prevAll().css('opacity','1');
});
$(this).click( function(){
//Clear all of them
$(this).parent().attr('value',$(this).attr('number'));
$(this).parent().children('#value-display').html($(this).attr('number') + ' / 5');
//Color up to the selected ones.
$('#ratingbar img').each( function(){
if($(this).attr('number') <= $(this).parent().attr('value')){
$(this).css('opacity','1');
}else{
$(this).css('opacity','.50');
}
});
});
$(this).mouseout( function(){
$(this).css('opacity','.50');
$(this).prevAll().css('opacity','.50');
//Color up to the selected ones.
$('#ratingbar img').each( function(){
if($(this).attr('number') <= $(this).parent().attr('value')){
$(this).css('opacity','1');
}
});
});
});
</script>
</html>

Save position of Jquery draggable DIVs using php

There are a lot of solutions out there as to how to save the position of draggable DIVs but I haven't found any that will help with using a While loop in php.
I have a database of "needs" and I want to display all the "needs" that match the persons username and status=inprogress. This could be 1 need or 1,000,000 needs depending on if the criteria is met.
I want to save the position of the need (DIV) automatically when it's moved. Is this possible? I wanted to store the values in a database using SQL if I can.
Here the code I currently have that displays the "needs" (divs)
Header
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css" />
<style>
#set div { width: 90px; height: 90px; padding: 0.5em; float: left; margin: 0 10px 10px 0; }
#set { clear:both; float:left; width: 368px; height: 120px; }
p { clear:both; margin:0; padding:1em 0; }
</style>
<script>
$(function() {
$( "#set div" ).draggable({
stack: "#set div"
});
});
</script>
Body
<div id="set">
<?
$query = mysql_query("SELECT * FROM needs WHERE (needsusername='$username' OR workerusername='$username') AND status='inprogress'");
while ($rows = mysql_fetch_assoc($query)) {
$title = $rows['titleofneed'];
$status = $rows['status'];
echo "
<div class='ui-widget-content'>
$title<br>Status: $status<br>
</div>
";
}
?>
</div>
Insert Query
$x_coord=$_POST["x"];
$y_coord=$_POST["y"];
$needid=$_POST["need_id"];
//Setup our Query
$sql = "UPDATE coords SET x_pos=$x_coord, y_pos=$y_coord WHERE needid = '$needid'";
//Execute our Query
if (mysql_query($sql)) {
echo "success $x_coord $y_coord $needid";
}
else {
die("Error updating Coords :".mysql_error());
}
You can use the stop event of draggable to get noticed when an element has reached a new position. Then you just have to get the offset as described in the docs.
Assuming you have a setup like that:
<div id="set">
<div data-need="1"></div>
<div data-need="2"></div>
<div data-need="3"></div>
<div data-need="4"></div>
<div data-need="5"></div>
</div>
I've used a data attribute to store the id of the "need", you can later on use that id to store the position of the "need" in the database.
Now as mentioned before, use the stop event to send an ajax call to the server with the id of the need and the x and y postion of it. Be aware hat this is the position of the screen so if you have different screen sizes you should probably use positions relative to a parent container with a desired position.
$(function() {
$( "#set div" ).draggable({
stack: "#set div",
stop: function(event, ui) {
var pos_x = ui.offset.left;
var pos_y = ui.offset.top;
var need = ui.helper.data("need");
//Do the ajax call to the server
$.ajax({
type: "POST",
url: "your_php_script.php",
data: { x: pos_x, y: pos_y, need_id: need}
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
});
});
This way every time a draggable element reaches a new positions e request will be sent to your_php_script.php. In that script you then only have to grab the post parameters and store them in the database.
There is a working fiddle, of course the ajax request is not working but you can see whats going on in the console.

How to attach an Event Handler for dynamically generated Child divs?

I have a page with 2 Div containers ( Left and Right ).
PartsList page has 5 dynamically generated DIVS.
Custom page has 5 dynamically generated DIVS.
The div with id "layout" isnt getting recognized with the jQuery .on(). Please help. Thank you for you time :).
<script type="text/javascript" src="js/jquery.js">
</script>
<script type="text/javascript">
$(function() {
$(".left").load("PartsList.php",function() {alert("success");});
$(".right").load("Custom.php", function() {alert("success");});
$("#layout").children().on({click: function() {
alert($(this).attr('id'));
}
});
});
</script>
<body>
<div class="main">
<div class="left">
//Load Left page.
</div>
<div class="right">
//Load Structure page.
</div>
</div>
</body>
</html>
PartsList
<?php
for ($x = 1; $x < 6; $x++)
{
$divs = <<<here
<div id = 'div$x' class = 'list'><strong>Div: $x</strong></div>
here;
echo $divs;
}
?>
Custom
<?php
echo '<div id="layout">';
for ($y = 0; $y < 5; $y++)
{
echo "<div id='x$y' style='
position: absolute;
width: 200px;
height: 100px;
top: ".(100 * $y)."px;
border: 2px solid blue;
cursor: pointer;
'></div>";
}
echo '</div>';
?>
in jquery 1.7+ use on like
$(document).on('click','dynamicElement',function(e){
//handler code here
});
in the earlier versions use delegate
$(document).delegate('dynamicElement','click',function(e){
//handler code here
});
you can replace the document with parent element of the dynamically generated element
From the Jquery online manual:
.load( url [, data] [, complete(responseText, textStatus, XMLHttpRequest)] )
url: string containing the URL to which the request is sent.
data: map or string that is sent to the server with the request.
complete(responseText, textStatus, XMLHttpRequest)A callback function that is executed when the request completes.
You probably need to put the .on function as a callback of the .load for that Custom.php page.
Something like this EXAMPLE:
$(function() {
$(".left").load("PartsList.php",function() {alert("success");});
$(".right").load("Custom.php", function() {alert("success");
$("#layout").children().on({click: function() {
alert($(this).attr('id'));
}
});
});
});
I think you've got the wrong syntax for the .on() function it should be something like:
$('document').on('click', '#layout > div', function() {
alert($(this).attr('id'));
});
You bind to the document and when a user clicks on a child div in layout the event 'bubbles' up the DOM to the document where it is caught.
Okay. I found the answer anyhow. For people who were thinking why it didnt work. It was because of the stupid QUOTES.
$("document") should have been $(document) since document isnt a tag <.
And tada thats it.
Sigh.
Thanks for the help everyone :)

Using JQuery UI's sortable('serialize') after loading data in via .load();

I have a page (page1.php) where I am using a select box to load in another page (page2.php) into a DIV. Inside page2.php there is a UL that loads data from a database (via PHP) into LIs and the are sortable.
My problem is, when I load page2.php by itself, it serializes fine. However, when page2.php is loaded via .load() into page1.php, it doesn't serialize at all and I get undefined.
Here is the important code, again this works fine by itself, but not when this page is loaded in via the .load() function
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
<style>
#thelist { list-style-type: none; margin: 0; padding: 0; width:700px; }
#thelist li { margin: 3px 3px 3px 0; padding: 1px; float: left; width: 200px; height: 150px; }
</style>
<ul id="thelist">
<li style="margin-bottom:5px;" name='listItem_1' id='listItem_1'>
test1
</li>
<li style="margin-bottom:5px;" name='listItem_2' id='listItem_2'>
test2
</li>
<script type="text/javascript">
$(function() {
$("#thelist").sortable({
update : function () {
var order = $('#thelist').sortable('serialize');
alert(order); // This alerts "undefined" when page2.php is loaded into page1.php via .load();
$("#info").load("reorder_slides.php?"+order);
}});
});
</script>
This is the new code I am running, still to no avail.
<script>
$('#edit_service_date').change(function() {
// $(this).val()
$('#editService').slideUp("slow",function(){
$('#thelist').load('page2.php', {id: $('#edit_service_date').val()}, function(){
$("#thelist").sortable({
update : function () {
var order = $('#thelist').sortable('serialize');
alert(order); // This alerts "undefined" when page2.php is loaded into page1.php via .load();
$("#info").load("reorder_slides.php?"+order);
}});
if($('#edit_service_date').val()!="none"){
$('#editService').slideDown("slow");
}
});
});
});
</script>
If everything you posted above is being brought into another page via .load(), then I see (at least) two problems:
You're loading jQuery and jQuery UI twice: once in the outer page, and once in the inner page loaded via ajax. There's no need.
You're expecting $(function(){}) to fire after being loaded into the "inner" page within the div. $(function(){}) is a synonym for $(document).ready( function(){} ), and in fact the ready event has already fired (when the outer page DOM became ready). It won't do anything here.
You should try triggering the .sortable() stuff inside the callback of the .load() you're using to bring the inner document into the div:
/* on page1.php */
$('#yourdiv').load( 'page2.php', function(){
$('#thelist').sortable( /* arguments */ );
});

Categories