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 + ')');
Related
So I'm working on my very first ever attempt at pagination (using simple Previous and Next buttons) on a for-fun project that I've undertaken. Below is all of the relevant code for my pagination system - I have left out the before and after, but I assure you that the table structure is valid.
Here is the jQuery I'm using with the elements I'm using to call the script:
<ul class="pager">
<li class="previous">< Previous</li>
<li class="next">Next ></li>
</ul>
<script>
$(document).ready(function() {
var page = 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
$('#pagination-prev').click(function() {
page = page - 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
});
$('#pagination-next').click(function() {
page = page + 1;
$(".pagination-page").hide();
$(".pagination-page tbody[id=page" + page + "]").show();
});
});
</script>
When I viewed the page without the jQuery active, I saw 8 <tbody> elements filled with dummy data that had been properly classed and id'd by the PHP script. My issue is that when I view the page with the script active, it doesn't seem to be working out for me. It hides all .pagination-page elements as I want, but my output has nothing toggled to show. Below is the PHP that is generating the content that I am flipping through.
<?php
try {
$listed = $dbc->query("SELECT data1,data2,data3,data4 FROM `table` ORDER BY data3 DESC")->fetchAll(PDO::FETCH_BOTH);
$annPP = 15;
$totalRows = count($listed);
$lastPCount = $totalRows % $annPP;
$totalPages = ceil($totalRows/$annPP);
$place = 0;
for ($i=1;$i<=$totalPages;$i++) {
echo "<tbody class='pagination-page' id='page{$i}'>";
if ($i == $totalPages) {
// Only do the remaining rows
$pageMax = $place + $lastPCount;
} else {
// Do 15 rows
$pageMax = $i * 15;
}
for ($j=$place;$j<$pageMax;$j=$place) {
$row = $listed[$j];
echo "<tr>
<td style='width: 25%'>";
if ($isAdmin) {
echo '<label class="control-label"><input type="checkbox" name="delete[]" value="' . $row['0'] . '"> ';
}
echo "<a href='view.php?id={$row[0]}'>{$row[1]}</a>";
if ($isAdmin) {
echo '</label>';
}
echo "</td>
<td style='width: 60%'>{$row[2]}</td>
<td class='text-center' style='width: 15%'>";
$created = new DateTime($row[3]);
echo $created->format('Y/m/d') . "</td>
</tr>";
$place++;
}
echo "</tbody>";
}
}
?>
What did I miss? What's going on? Thanks!
Removing the .pagination-page to make my jQuery read as follows:
$("tbody[id='page" + page + "']").show;
Fixed the problem. Not quite sure I understand why this is, though.
if(boothsizerGlobal == 3){
var cellWidth = 112;
var cellHeight = 52;
var innerDivElectricTop = 41;
var innerDivElectricLeft = 110;
$('.imgBox').css("background-image", "url(booth_top_images/5X20TOP.jpg)");
$('.imgBox').css("width", "900px");
$('.imgBox').css("height", "225px");
sidewalls = 2;
backwalls = 6;
}
Can anybody help me on converting above code into PHP?
I mean how to set CSS for a DIV in more than 40 if conditions I have?
Thanks
.imgBox
{
background:url(booth_top_images/5X20TOP.jpg) no-repeat;
width:900px;
height:225px;
}
Well, your original code made no sense to begin with as half of the declared variables weren't even being used. Furthermore, it is beyond me why you'd want to convert front-end code into server-side code like this, php is not the right way to do this!
if(boothsizerGlobal == 3){
$cellWidth = '112px';
$cellHeight = '52px';
$innerDivElectricTop = '41px';
$innerDivElectricLeft = '110px';
$backgroundImage = 'url(booth_top_images/5X20TOP.jpg)';
$divCode = '<div style="width: ' . $cellWidth . '; height: ' . $cellHeight . '; "';
return $divCode
}
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.
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']
I've got the following code, and the stuff before the javascript echos and the stuff after the javascript includes, but the javascript won't echo :/
$currentPage = $_POST["current_page"];
$nextPage = 1 + $currentPage;
$count = $_POST["cum_count"];
$total = $_POST["cum_total"];
$progress = $_POST["cum_progress"];
echo $currentPage . $nextPage;
# number of questions less 1
$numQs[2]=6;
$numQs[3]=3;
$numQs[4]=5;
$numQs[5]=34;
$numQs[6]=17;
$numQs[7]=43;
$falses = array('false');
for ($i=0; $i < $numQs[$nextPage]; $i++) {
array_push($falses,', false');
}
# the js is how the survey keeps track of where it is
echo "<script type='text/javascript'>\n
var c_name = 'whbssurvey';\n
var c_value = '$nextPage';\n
document.cookie=c_name + '=' + c_value;\n
// set survey info\n
var count = $count;\n
var total = $total;\n
var progress = $progress;\n
var qArray = [$falses];\n
</script>";
include("$nextPage.php");
P.S. In case anyone is thinking cum_count is something dirty, it's short for cumulative.
Are you sure it's not echoing? It's being done BEFORE you do your include. If that include is a complete html page, the JS would be echoed BEFORE the opening <html> tag (which makes for an invalid page).
As well, for dumping out multiline text like that, you should either drop out of PHP mode so it's just plaintext that'll get echoed out automatically, or use a HEREDOC. Since you're inserting a couple PHP vars into that output, the HEREDOC would probably be preferable.
Try echoing without the <script> and </script> tags. It's possible that it is being printed but your browser isn't rendering it for some reason. If you get all the code spewed on the page, it worked.
try:
echo "<script type='text/javascript'>\n" .
"var c_name = 'whbssurvey';\n" .
"var c_value = '$nextPage';\n" .
"document.cookie=c_name + '=' + c_value;\n" .
"// set survey info\n" .
"var count = $count;\n" .
"var total = $total;\n" .
"var progress = $progress;\n" .
"var qArray = [$falses];\n" .
"</script>";