Save position of Jquery draggable DIVs using php - 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.

Related

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>

how to show friendly message while task completes

I don't know if I've even asked the question properly, but I have a codeigniter application that some heaving lifting in the back end. While the app is busy executing commands(ajax commands), I'd like to show some sort of a status / message box / div. When the task is done, I'd like to clear the div / box.
What would I need to google to find a solution like this?
Thanks.
Edit:
This is what my jquery / ajax call looks like right now...
$('#availVLANS').click(function() {
$(this).attr("disabled","disabled");
$.ajax({
url:"<?php echo site_url('controller/methodABC/');?>",
type:'POST',
dataType:'json',
success: function(returnDataFromController) {
var htmlstring;
var submitFormHTML;
htmlstring = "<br><br><B>To reassign the port to a new vlan, click on a VlanId below and then click on the OK button</B><br><table class='table table-bordered table-striped'>";
htmlstring = htmlstring + "<th>VlanId</th><th>Name</th>";
for(i = 0; i < returnDataFromController.length; i++) {
//alert(returnDataFromController[i].VlanId);
htmlstring = htmlstring + "<tr><td><a href=>"+returnDataFromController[i].VlanId+"</a></td><td>"+ returnDataFromController[i].Name+"</td></tr>";
}
submitFormHTML = "<form method='post' accept-charset='utf-8' action='" + BASEPATH + "index.php/switches/changeportvlan/"+ $('#ip').val() +"/" + $('#hardwaremodel').val() +"/" + $('#port').val() + "'><input type='text' name='newVlanID' id='newVlanID' style='width:5em;height:1.5em'/> <button type='submit' class='btn' name='saveVlan' id='saveVlan' style='width:10em;height:2em'>Reassign Vlan</button></form>";
//alert(submitFormHTML);
$('#clientajaxcontainer').html(htmlstring);
$('#newvlanform').html(submitFormHTML);
}
});
$(this).removeAttr("disabled");
});
Just use an animated GIF image in an absolutely positioned DIV overlayed on top of the whole page. Just make sure that you overlay an invisible DIV over top of the entire page to prevent clicks on interface elements behind the progress window. Something like this;
╔════════════════════╗
║ #progress-overlay ║
║ ╔════════════════╗ ║
║ ║ #progress-indicator
║ ╚════════════════╝ ║
╚════════════════════╝
The #progress-overlay is a background for the indicator and what you're going for is like a LightBox2 effect but using a progress indicator and small box in the middle of the screen.
You can get animated gif's from here;
http://preloaders.net/
Make sure that your progress/something-is-happening div sits at the top level of the document structure, so somewhere at the top of the body, before any of your other container DIV's. This is done so that the #progress-overlay is rendered at the same level in the DOM as the top level element of your website. When you absolutely position the #progress-overlay, it will appear overtop of everything else on the page.
<html>
<head>
....
</head>
<body>
<div id="progress-overlay">
<div id="progress-indicator">
<img src="images/myprogress.gif" /> Please Wait...
</div>
</div><!--progress-overlay-->
<div id="website-wrapper">
.... web site, layout, content, etc...
</div>
</body>
</html>
The #progress-overlay is hidden by default and then shown overtop when needed. Something like;
#progress-overlay{
position: absolute;
width: 100%;
height: 100%;
background: #000;
opacity: 0.2;
}
#progress-indicator{
position: relative;
margin: 0 auto;
top: 40%;
width: 200px;
height: 50px;
}
Using JQuery you could easily make this appear on demand using;
$(document).ready(function(){
$('#progress-overlay').hide();
});
function showProgressIndicator()
{
$('#progress-overlay').show();
}
You can make use of onreadystatechange event:
http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp
If you're doing it through jquery, just show a div with a message and/or a spinner.
jQuery.ajaxSetup({
beforeSend: function() {
$('#loader').show();
},
complete: function(){
$('#loader').hide();
}
});
If you're using jQuery, I propose the following solution:
The jQuery:
$(document).ready(function(){
$("#the_button").click(function(){
var url = "the_controller/the_method"
var data = {the: "data"}
//before the POST takes place, fade-in the message
$("#the_message").fadeIn();
$.post(url, data, function(r){
if(r.success){
//when the post is finished, and it was successful, fade-out the message.
$("#the_message").fadeOut();
}
else console.log("something bad happened");
}, 'json');
});
});
The HTML:
<!-- HIDE IT BY DEFAULT -->
<div id='the_message' style='display:none;'>
Please wait.
</div>
The Controller:
class The_controller extends CI_Controller{
function the_method(){
$p = $this->input->post();
the_task($p);
if(the_task_success) return json_encode(array("success" => true));
else return json_encode(array("success" => false));
}
}

jquery display loading text on keypress

I need the jquery script for the following
while typing inside the text field, the 'Load' text need to be displayed near the text field.
If i stop typing the 'Load' text need to change as 'Del'
If click this 'Del' Text the text field should be cleared.
In the mean time i need to display the search result for the entered text.
For this i used the following script
$("#lets_search").keyup(function() {
var value = $('#str').val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
return false;
});
});
Here is the html part of the file
<form id="lets_search" action="" style="width:400px;margin:0 auto;text-align:left;">
Search:
<div> </div>
<div style="float:left; width:250px;">
<div style="background-color:#fff; padding:3px; width:200px; float:left; border-left:1px solid #eee; border-top:1px solid #eee; border-bottom:1px solid #eee;">
<input name="str" id="str" type="text" style="border:0px; width:150px;">
<div style="float:right; padding-top:3px;" id="loader">Load</div>
</div>
</div>
</form>
<div id="search_results"></div>
In this <div style="float:right; padding-top:3px;" id="loader">Load</div>
I have to display the text (del, Loading etc...)
Please do the needful. Thanks
I think the best way to do this is with a setTimeout, like so:
var pTimeout = null;
$("#lets_search").keyup(function()
{
var value = $('#str').val();
$('#loader').text('Loading...').unbind('click');
if(pTimeout) clearTimeout(pTimeout);
pTimeout = setTimeout(function () { GetResult(value); }, 50);
});
function GetResult(value)
{
$.post('db_query.php',{value:value}, function(data){
pTimeout = null;
$('#loader').text('del').click(function () {
$("#search_results").empty();
$('#str').val('');
});
$("#search_results").html(data);
});
}
There is always a better way of doing it, but must give you the idea.
PS I did not test the code :)
var searchTimeout = null;
$("#str").keyup(function() {
// Clear any existing timeout
if (searchTimeout) {
clearTimeout(searchTimeout);
}
// Put "Load" text in
$('#loader').html('Load');
// Set a timeout for end of typing detection
searchTimeout = setTimeout(function() {
$('#loader').html('Del');
}, 500);
// Get the value from the text field and send it to the server
var value = $(this).val();
$.post('db_query.php',{value:value}, function(data){
$("#search_results").html(data);
});
});
// Clears the search box value
function clearSearch() {
$("#str").val('');
};

How to Submit and Display on the same page using jQuery and MySQL?

Goal:
Create a Q&A Script (using PHP, JavaScript and jQuery) that enables users to ask questions and submit answers to said questions.
If the user submitted a new answer, that answer would be inserted into the database and the div containing the answers would be refreshed automatically to include/view that newly submitted answer.
Problem:
After submitting the answer, the submission process is not working.
Here is my code:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script language="JavaScript">
$(document).ready(function ()
{
/*Function # 4:
Hide the AnswerForm and show Answers where the div will be automatically refreshed upon answer submission. <>>>> REVIEW!!! */
function addAnswer(i,qID)
{
//alert("newanswer-q"+i);
//$("newanswer-q"+i).style.display("none");
//$("Answers-q"+i).style.display("block");
changeDiv("Answers-q"+i, "block");
//step # 1: define posted data to insert into database
var name = $("input#name").val();;
var answer = $("input#answer").val();;
alert(name+","+answer);
//step # 2: submit form to be processed by CHANGE.PHP to insert into DB
$.ajax({
type:"POST",
url:"change.php",
data: "questionID="+qID+"&count="+i+"&name="+name+"&answer="+answer,
success: function(data)
{
if(data==0)
{
alert("YEEEEEEEEEESSSS!!!!!! :DDDDDD");
$("#Answer-q"+i).html("Finally!");
}
else
{
$("#Answer-q"+i).html("?!?!");
}
}
});
//Step # 3: refresh Answers div
//changeDiv('Answers-q'+i, 'block');
$("#Answers-q"+i).load("printAnswers.php");
}//end addAnswer
$("#refreshAnswers").click(function(evt){
$("#refreshAnswers").load("printAnswers.php");
evt.preventDefault();
});
}
</script>
<style type="text/css">
.answers
{
background-color: red;
position: relative;
display: block;
left: 1in;
}
.answerform
{
background-color: yellow;
position: relative;
display: block;
left: 1in;
}
.error
{
color: red;
display:none;
}
</style>
</head>
<body>
<?php
mysql_connect("#", "#", "#") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$q1 = "SELECT *
FROM questions";
$allQ = mysql_query($q1);
while($q = mysql_fetch_array($allQ))
{
$i = $q['qID'];
echo '<div id="questions" style="background-color: blue;">';
echo 'Question: '.$q['Question'].'<br><br>';
echo 'posted by '.$q['userName'].'<br><br>';
echo 'posted on '.$q['addDate'].'<br><br>';
echo '</div>';?>
<input type="button" id="viewAnswers" name="viewAnswers" value="View Answers" onClick="changeDiv('Answers-q<?=$i?>', 'block');">
<input type="button" id="addAnswer" name="addAnswer" value="Answer Question" onClick="changeDiv('newanswer-q<?=$i?>', 'block');">
<div id="Answers-q<?=$i?>" class="answers">
<? include("printAnswers.php"); // display all answers to question # i
?>
</div>
<? echo '<div id="newanswer-q'.$i.'" class="answerform">';
include("addAnswerForm.php"); // display add new answer to question # i
echo '</div>';
} ?>
<br>-------------------------<br>
Go back to index.php
</body>
</html>
Change.php
<?php
mysql_connect('#', '#', '#') or die(mysql_error());
mysql_select_db('test') or die(mysql_error());
// Get values from form
$name=$_POST['name'];
$answer=$_POST['answer'];
$qID = $_POST['qID'];
// Insert data into mysql
$sql="INSERT INTO answers(Answer, userName, qID)
VALUES('$answer', '$name','$qID')";
$result=mysql_query($sql);
?>
I have been stuck on this for a couple of hours now with no luck thanks to my beginner-level skills in both PHP and jQuery.
Can anyone throw me a lifeline or something?
What's the value of data? Try console.log(data) in your success function. Seems to me change.php doesn't produce any output, so why should data equal zero ?
Your data appears to be sent via "GET" request.
Change te AJAX data object to this:
data : {
questionID : qid,
count : i,
name : name,
answer : answer
}
If you pass it as a string the way you did, it gets appended to the URL (becoming a GET request), if you pass it as an object it gets posted.

Sortable Portlet Update Query

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>

Categories