jQuery Sortable PHP - php

I am using jQuery sortable to manipulate image order and write to a DB. That functionality works well.
PHP
echo "<div class='revisionNum'>";
echo "<ul id='sortable_" . $count ."'>";
while($row = mysql_fetch_array($result)) {
$sortImageName = $row['OrgImageName'];
$sortPath = "../data/gallery/" . $galleryID . "/images/album/" . $sortImageName;
echo "<li class='sortPhotos' id='item_{$row['id']}' >";
echo '<img class="sortImage" src="'. $sortPath .'"/>';
echo "<p>" . $sortImageName . "</p>";
echo "</li>";
}
echo "</ul>";
echo "</div>";
jQuery
//make sortable
$(".revisionNum").each(
function(e) {
num = e + 1;
$("#sortable_" + num).sortable(
{stop:function(i) {
serial = $("#sortable_" + num).sortable("serialize");
$.ajax({
type: "GET",
url: "../albumUploader/queries/sort.php",
data: serial
});
},
opacity:1.0,
//cursor: move
});
});
MYSQL
foreach($_GET['item'] as $key=>$value) {
mysql_query(" UPDATE galleryimage
SET sort = '{$key}'
WHERE id = '{$value}'
");
}
The issue is when I have multiple <div class=''revisionNum> i am only grabbing the serial = $("#sortable_" + num) of the last UL if the [.revisionNum], not the actual UL that I am sorting. Thanks for the help on this. Let me know if further clarification is needed.

I am not sure I fully understand your question, but I think you are looking for the following:
The variable num will change every loop you make in the each-loop. But at the end it will have the value of the last loop. Because num seems to be a global variable you can't call it in the stop function. Then it will just use the last value it had. The value of the last loop. (Explains your problem)
To solve this I recommend to change your code to:
$(".revisionNum").each(
function(e) {
$(this).children("ul").sortable(
{stop:function(i) {
num = $(this).children("ul").attr("id").replace("sortable_", "");
serial = $(this).children("ul").sortable("serialize");
...
$(this) refers to the $(".revisionNum") you are looping through and it will be remembered, also in the stop function.

Related

Ajax Div Refreshing Too Fast

I have a form that posts to a script via ajax, the script inserts the form data into a database and using ajax i the refresh the div on the original page which then shows the form as well as a list of records in the database (from the form input)
I hope that makes sense.
My issue is that sometimes, maybe 1 time in 20, the div refreshes too quickly and doesn't pick up on the new data if i refresh the page its there and if i submit a new record both records are then in the list.
I guess i just need to delay the refreshing but i don't know how.
thanks,
php
echo '<div id="cuttingListDiv">';
$sql = "SELECT * FROM `cuttingList` WHERE jobRef = '".$_SESSION["jobRef"]."' ORDER BY pieceMaterialName, pieceThickness ASC";
$results = $dbconn->query($sql);
if ($results->num_rows > 0) {
echo '<h3>Cutting List:</h3>';
echo '<div align="center">';
while($row = $results->fetch_assoc()) {
echo '<br />';
echo '<div class="row">';
echo '<div class="col" align="center">';
echo '<h5>'.$row["pieceMaterialName"] . ' - ' . $row["pieceLength"] . ' x&nbsp' . $row["pieceWidth"] . ' x&nbsp' . $row["pieceThickness"] . 'mm</h5>';
echo '<br />';
echo '</div>';
echo '</div>';
}
echo '</div>';
}
echo '</div>';
ajax script
session_start();
include '_script_sqlConnection.php';
$pieceLength = strip_tags($_POST['pieceLength']);
$pieceWidth = strip_tags($_POST['pieceWidth']);
$thickness = strip_tags($_POST['thickness']);
$material = strip_tags($_POST['material']);
$materialName = strip_tags($_POST['materialName']);
$sheetID = strip_tags($_POST['sheetID']);
// Swap width & length id width bigger
if ($pieceWidth > $pieceLength) {
$tmpDimm = $pieceLength;
$pieceLength = $pieceWidth;
$pieceWidth = $tmpDimm;
}
$sql = "INSERT INTO `cuttingList`(`orderRef`, `pieceMaterialName`, `pieceThickness`, `pieceLength`, `pieceWidth`, `sheetID`, `pieceWeight`, `qty`) VALUES ('".$_SESSION["quoteRef"]."', '".$materialName."', '".$thickness."', '".$pieceLength."', '".$pieceWidth."', '".$sheetID."', '".$pieceWeight."', '1')";
if ($dbconn->query($sql) === FALSE) {
echo "Error Adding Pieces To Cut List.<br />";
}
javascript
$("#cuttingListForm").submit(function(){
$.ajax({
type: "POST",
url: "_script_ajax_addToCuttingList.php",
data: $('form.cuttingListForm').serialize(),
success: function() {
$("#cuttingListDiv").load(location.href + " #cuttingListDiv");
}
});
});
Use the JS function setTimeout
// example of usage for setTimeout:
setTimeout( function(){
$("#cuttingListDiv").load(location.href + " #cuttingListDiv");
}, 2000 );
In the example you have 2000 milliseconds for 2 second wait before fired the call.
Thanks for you help but i went a different way as i was still having trouble with both of these methods.
At the very top of the div that refreshes I used the php sleep command to wait 1 second, now it works perfectly.
Thanks,

Change img to background image in PHP loop jQuery

I'm trying to convert loaded imgtags to background images using jQuery, however, the images are being loaded in a PHP while loop. When I try implementing the jQuery, only the last img tag is looked at by the jQuery. Here is my code
PHP
$query = mysqli_query($dbleads, "SELECT * FROM plugin_blog WHERE published = 1 ORDER BY date_added DESC LIMIT 0,20");
$i = 0;
$j=-1;
while ($row=mysqli_fetch_array($query)){
preg_match('/(<img[^>]+>)/i', $row['html'], $matches);
$img = $matches[1];
++$i;
if ($i%2 == 0){
++$j;
echo "<div class='masonryImage tweets' style='width:300px; height:175px;'><div class='tweet-content'>" . $tweets[$j] . "</div></div>";
}
else{
echo "<div class='masonryImage blogImage' style='width: 300px; height:200px;'>" . $img . " </div>";
}
}
jQuery
$j('div.blogImage img').each(function() {
var imageSrc = $j(this).attr('src');
$j(this).remove();
$j('.blogImage').html('<div class="backbg"></div>');
$j('.backbg').css('background-image', 'url(' + imageSrc + ')');
$j('.backbg').css('background-repeat','no-repeat');
$j('.backbg').css('background-position','center');
$j('.backbg').css('background-size','cover');
$j('.backbg').css('width','100%');
$j('.backbg').css('height','100%');
});
Any ideas?
You are setting every .backbg's css on the last iteration.
When you run $j('.backbg').css('background-image', 'url(' + imageSrc + ')'); the last time, you are saying "find EVERY .backbg, even the ones I've already done, and set their css".
You need to do something like:
var imageSrc = $j(this).attr('src');
var blogImg = $j(this).parent();
$j(this).remove();
blogImg.html('<div class="backbg"></div>');
blogImg.find('.backbg').css('background-image', 'url(' + imageSrc + ')');

how to differentiate between these entries?

I have a new question about a project I had been working on. I was designing a grid with different colored cells. it has a hidden div which shows when a cell is clicked, however I realized that only one cell(the last one of it's type) will show. i.e. if I have 2 objects with the column "objaffinity" as 0 ("enemy") it will show both red cells on the grid, however only the last one will actually work.
how can I make it so that it will show the proper information for each cell?
here's my code:
mapgen.php:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="cellinfo.js"></script>
<script src="cmenu.js"></script>
<?php
require("sql.php");
$sql = <<<SQL
SELECT *
FROM `maps`
WHERE `objpresent` = 1
SQL;
if(!$result = $db->query($sql)){
die('There was an error running the query [' . $db->error . ']');
} // ran the query
//$xobj = array();
//$yobj = array();
$otype = array();
$oname = array();
$xyobj = array();
while($row = $result->fetch_assoc()){
$xyobj[$row['x']][$row['y']] = true;
$otype[$row['id']]=$row['objaffinity'];
$oname[$row['id']]=$row['object'];
}
// get the rows
$cellid=1;
//find whether the row is obstructed
for ($y = 0; $y < 20; $y++) {
echo '<tr>';
for ($x = 0; $x < 25; $x++) {
echo "<td>";
//Detect what type of object it is
if (isset($xyobj[$x][$y])) {
if($otype[$cellid] == 2)
{
echo "<a href='#'> <div class='foe'> </div><div class='foepopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
elseif($otype[$cellid] == 1)
{
echo "<a href='#'><div class='friend'></div><div class='friendpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
else
{
echo "<a href='#'> <div class='neutral'></div><div class='neutralpopup'>";
echo $oname[$cellid];
echo "</div></a>";
}
$cellid++;
}
echo '</td>';
}
echo '</tr>';
}
?>
Cellinfo.js:
$(document).ready(function(){
//initially hide all popups
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").hide();
//foebutton selected
$(".foe").on("click",function(e){
$(".friendpopup").hide();
$(".neutralpopup").hide();
$(".foepopup").show();
});
//close foe when selected
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
//neutral button pressed
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
//close neutral
$(".neutralpopup").on("click",function(e){
$(".neutralpopup").hide();
});
//friend button pressed
$(".friend").on("click",function(e){
$(".foepopup").hide();
$(".neutralpopup").hide();
$(".friendpopup").show();
});
//close friend
$(".friendpopup").on("click",function(e){
$(".friendpopup").hide();
});
});
In your functions you use selectors, so for the script it does not matter which div was clicked.
Let me show you some examples:
$(".foepopup").on("click",function(e){
$(".foepopup").hide();
});
It should be something like this rather:
$(".foepopup").on("click",function(e){
$(this).hide();
});
And another example:
$(".neutral").on("click",function(e){
$(".foepopup").hide();
$(".friendpopup").hide();
$(".neutralpopup").show();
});
Rewrite it like this:
$(".neutral").on("click",function(e){
var td_tag = $(this).parent().parent();
td_tag.children(".foepopup").hide();
td_tag.children(".friendpopup").hide();
td_tag.children(".neutralpopup").show();
});
Rewrite other code on your own. this is the element on which click was triggered. td_tag will contain parent cell of a div clicked. After that, children method will allow you to find needed elements already inside specific cell.
Good luck!

Option on dropdown as anchor

I am pulling out record from the database and inserting them inside a dropdown like this:
echo "<select>";
while ($drow = mysql_fetch_assoc($request))
{
echo "<option>" . $drow['id'] . "</option>";
}
echo "</select>";
It works but I need to be able to click on an option on the dropdown and make it link just like:
Record1Here
Record2Here
Record3Here
UPDATE: Latest code:
<script>
function doSomething() {
var currentval = this.options[this.selectedIndex].value;
// you could navigate away at that point ?
window.location = currentval;
}
</script>
...
echo "<select onchange='doSomething();'>";
while ($drow = mysql_fetch_assoc($request))
{
echo "<option value=\"view.php\">" . $drow['id'] . "</option>";
}
echo "</select>";
You can't place anchors on an option within a select list.
What you can do is use JavaScript and then do something on the change event of the select list :
echo "<select onchange='doSomething(this);>';
then in JavaScript do something based on the selected value :
function doSomething(elem) {
var currentval = elem.options[elem.selectedIndex].value;
// you could navigate away at that point ?
window.location = currentval;
}
Example here
you could update your PHP code to include a value in each option :
echo "<option value=\"urlhere.php\">" . $drow['id'] . "</option>";

jquery add to array then submit and pass data not working

My problem is:
I'm trying to submit an array of hidden input types, which are stacked into an array using jquery onclick, to a PHP file. However, when I try to count or even echo the passed variable in the php file (saveTest.php), no data appears or the count variable is zero.
I've searched and I found this guy's question:
pass an array from jQuery to PHP (and actually go to the page after submit)
I think I'm close to the above post but I'm still a newbie in jQuery so I don't understand much of the codes.
This is my jquery:
$(function(){
$("td").click(function(){
if($(this).hasClass("on"))
{
alert("Already marked absent");
}
else
{
$(this).addClass("on");
var currentCellText = $(this).text();
$("#collect").append("<input type='text' hidden = '" + currentCellText + "'/>" + currentCellText);
}
});
$("#clicky").click(function(){
$("td").removeClass("on");
$("#collect").text('');
$("#collect").append("Absentees: <br>")
});
});
<?php
session_start();
include 'connectdb.php';
$classID = $_SESSION['csID'];
$classQry = "SELECT e.csID, c.subjCode, c.section, b.subj_name, e.studentID, CONCAT(s.lname, ', ' , s.fname)name
FROM ENROLLMENT e, CLASS_SCHEDULE c, STUDENT s, SUBJECT b
WHERE e.csID = c.csID
AND c.csID = '" . $classID . "'
AND c.subjCode = b.subjCode
AND e.studentID = s.studentID
ORDER BY e.sort;";
$doClassQry = mysql_query($classQry);
echo "<table id='tableone'>";
while($x = mysql_fetch_array($doClassQry))
{
$subject = $x['subj_name'];
$subjCode = $x['subjCode'];
$section = $x['section'];
$studentArr[] = $x['name'];
$studentID[] = $x['studentID'];
}
echo "<thead>";
echo "<tr><th colspan = 7>" . "This is your class: " . $subjCode . " " . $section . " : " . $subject . "</th></tr>";
echo "</thead>";
echo "<tbody>";
echo "<tr>";
for($i = 0; $i < mysql_num_rows($doClassQry); $i++)
{
if($i % 7 == 0)
{
echo "</tr><tr><td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
else
{
echo "<td id = '". $studentID[$i] . " '>" . $studentArr[$i] . "</td>";
}
}
echo "</tr>";
echo "</tbody>";
echo "</table>";
?>
This is my php file (saveTest.php)
<?php
$absent = $_POST['absent'];
//echo "absnt" . $absent[] . "<br>";
echo count($absent);
?>
Add name to hidden field:
$("#collect").append("<input type='hidden' name="absent[] value= '" + currentCellText + "'/>" + currentCellText);
It looks like you want to submit a javascript array to a php script and then make use of it. You can make use of .each() function to loop through all the hidden values and adding them into the array. Then use $.post to submit the array to a php script.
<script src="jquery.js"></script>
<script>
$(function(){
$('#btn_submit').click(function(){
var array_hidden = [];
$('input[type=hidden]').each(function(index){
var current_value = $.trim($(this).val());
array_hidden[index] = current_value;
});
$.post('arraysubmit.php', {'hidden_array' : array_hidden}, function(data){
$('#results').html(data);
});
});
});
</script>
<?php for($x=0; $x<=10; $x++){ ?>
<input type="hidden" name="name[]" value="Name<?php echo $x; ?>">
<?php } ?>
<input type="button" id="btn_submit">
<div id="results"></div>
You can then access the array in the php script using the post variable and do whatever you want with it:
$_POST['hidden_array']

Categories