i'm doing a project for my school whereby i have to retrieve student works from database.
On my home page, i have preset 10 div to hold the data returned from query. I preset it because i only need to retrieve 10 data.
HTML
<div class="viewport-computer col-lg-12 visible-lg no-padding ">
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption">Author<br />Description</h2>
</div>
</div>
Then i use jquery to query to my php to get back 10 data and place onto my 10 div
Jquery
/* Home Page Autoload featured thumbnails based on computer viewport/mobile viewport
================================================== */
$.ajax({
type: "POST",
dataType: "json",
url: "CMS/PHP/displayFeatThumbs.php",
success: function(data) {
// Display image thumbnail, caption & description of works onto each thumbnail div
$('.viewport-computer .img_thumb_holder img').each(function(index, element) {
// Work out the data to set
var imageUrl = "cms/" + data[index].links;
var captionHtml = "<span>" + data[index].caption + "<span class='spacer'></span><br/><span class='spacer'></span>" + data[index].title + "</span>"
// Now apply this to the elements
$(element).attr("src", imageUrl); // i must find a way to solve this
$(element).parent().css('background-image', 'url("'+imageUrl+'")');
$(element).next().html(captionHtml);
// push the caption & id into global variable array to be used on other functions easily
captionArray.push(data[index].caption);
idArray.push(data[index].id);
homeLinksArray.push(data[index].links);
homeTitleArray.push(data[index].title);
});
});
It's working fine since i loop through my preset div(10 of them) and then place the data into each div.. Now i need to do a search bar function, and it will return me ALL the results(more than 50), and i have to display all of them, now the problem is that i only preset 10divs, so my workflow is not good for this
so instead of my current
loop through 10 div > retrieve data and place on 10 div
i would like to
retrieve all data, for each data, append a new div and place it
i am not very good with php as i'm still a new learner so i'm stuck at this although i have the idea on how to do it. Can someone enlighten me on how i can loop through each data and append instead of my preset divs?
PHP
<?php
include 'dbAuthen.php';
$searchBar = $_POST['searchBar'];
$sql = "SELECT userdatafiles.UserID,Name,Link,Title FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Skillsets = '$searchBar' GROUP BY UserID ORDER BY RAND()";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div>hi</div>',
$links[] = array(
"id" => $row["UserID"],
"links" => $row["Link"],
"caption" => $row["Name"],
"title" => $row["Title"],
);
}
//shuffle($links);
echo json_encode($links);
} else {
echo "0 results";
}
?>
Solution is not to preset 50 divs or 10 divs in your UI.
Simply when you retrieve your result loop through all records and at the same time instead of populating your divs you create divs on the fly and insert data to it. When newly created divs are ready append them to your UI with some classes like 'new-data' or something to give a look that these records are somewhat new in your UI.
Assuming data represent your json returned by PHP and data is collection of all records here is one way to do it
for(i=0; i<data.length; i++)
{
$('<div class="col-lg-2 img_thumb_holder no-padding new-class">'
+'<img src="'+data[i].imgSrc+'" class="img_thumb">'
+'<h2 class="caption">'+data[i].author+'<br />'+data[i].description+'</h2>'
+'</div>').appendTo("ul#yourRecordHolderElemenet").slideDown("fast");
}
Exact solution might depend on your json returned by PHP untill you show your exact json response we won't be able to help you properly.
I won't recommend returning data with their html markup being returned from PHP as it would increase amount of data being transferred.
Since you already have the information in database, add them directly in HTML rather than making a ajax request.
<div class="viewport-computer col-lg-12 visible-lg no-padding ">
<?php
//You can get 10 records from database using 'limit 10' added to select query.
//Get data from database. I assume you have the data in a variable $datafromdb
foreach($datafromdb as $data){
?>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption"><?=$data['author']?><br /><?=$data['description']?></h2>
</div>
<?php } ?>
</div>
Without writing complete code for you here is a step by step how you could do this
Create a database connection with mysqli or pdo
Select all records with a select query
Do a foreach on the resultset
Add one div in the foreach
PHP will add a div for each row in the select query
for example:
foreach($result->fetch_array() as $row) {
?>
<div class="col-lg-2 img_thumb_holder no-padding">
<img class="img_thumb">
<h2 class="caption"><?= $row['author'] ?><br /><?= $row['description'] ?></h2>
</div>
<?php
}
PHP Code should be :
<?php
include 'dbAuthen.php';
$searchBar = $_POST['searchBar'];
$sql = "SELECT userdatafiles.UserID,Name,Link,Title FROM userdatafiles JOIN users ON userdatafiles.UserID = users.UserID WHERE Skillsets = '$searchBar' GROUP BY UserID ORDER BY RAND()";
$result = mysqli_query($con,$sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
echo '<div>hi</div>',
$links = array(
"id" => $row["UserID"],
"links" => $row["Link"],
"caption" => $row["Name"],
"title" => $row["Title"],
);
}
//shuffle($links);
echo json_encode(array('contents' => $links));
} else {
echo "0 results";
}
?>
notice single dimension $link array and an associative array to json_encode.
In jQuery, your success: can/will be :
success: function(data){
$.each(data.contents, function(ind, ele){
// ele.id is the id and etc... or ind.id. :D
});
}
Related
I apologize for the such a bad question title, but I couldn't come out with something better. I will try to explain my problem in a brief manner so that this community will face less difficulty in understanding my problem.
Currently I am working on a CMS project and I am responsible for developing templates for that CMS. All the components of a template are being loaded dynamically on the basis of whether they have been activated or not in the admin panel, and they are being dynamically loaded on frontend using PHP code which is echoing the HTML code.
The problem is much related to updating and maintaining the templates as the number of templates is getting increased.
When there is some change needed to be made in the php code, then if number of templates is 1 or 3 then updating the same php code in other templates is not that difficult, but if the number templates increases like up to 10 or more than it will become a difficulty and will be time consuming.
I am looking for a way by which I can separate the php code from the HTML. So that when a change is required to be made in the php then it should be implemented once and it affects all the templates, rather than updating each templates php code.
I hope I am able to explain my problem correctly, but if still some information is missing then please let me know.
Updated question with code sample for better explanation.
In the code sample I am loading html elements based on conditions. Now if I need to make change in this php code and I have five different template which use the same code then I need to update it five times in five different files.
I am looking a for way to separate this php code from html.
echo'
<div class="section my-common-section" id="section-'.$j.'>
<div class="its_section_inner container-fluid my-4">
<!-- Master Row -->
<div class="row">
<div id="product-specifications-container" class="container mt-5">';
if(isset($a->heading) && !empty($a->heading)) {
echo '
<div class="row">
<h3 class="subsec-title subsec-title-border text-center mt-3 mb-2">'.htmlspecialchars_decode($a->heading).'</h3>
</div>';
}
echo'
<div class="row">';
$col1=$col2=false;
if(!empty($a->video) || (!empty($a->image) && file_exists($_SERVER['DOCUMENT_ROOT']."/da/uploads/".$sub."/section/".$a->image))) {
$col1 = true;
}
if(!empty($a->para)) {
$col2 = true;
}
// if both video and paragraph options are available
if($col1 && $col2) {
if(!empty($a->video)) {
echo '
<div class="col-12 col-md-4 col-xl-4">
<div class="col-content wow animate__animated animate__fadeIn">
<iframe width="100%" style="min-height:'.$a->videoheight.'px;" src="'.$a->video.'?rel=0&modestbranding=1" frameborder="0" allowfullscreen=""></iframe>
</div>
</div>';
}
else if(!empty($a->image) && file_exists($_SERVER['DOCUMENT_ROOT']."/da/uploads/".$sub."/section/".$a->image)) {
echo '
<div class="col-12 col-md-4 col-xl-5">
<div class="col-content wow animate__animated animate__fadeIn">
<img class="" src="'. base_url() .'da/uploads/'. $sub .'/section/'. $a->image .'" alt="'. $a->title .'" title="'. $a->title .'">
</div>
</div>';
}
echo'
<div class="col-12 col-md-8 col-xl-7">
<div class="col-content wow animate__animated animate__fadeIn">
'. $this->customlib->cleanTable(nl2br(htmlspecialchars_decode($a->para))) .'
</div>';
}
// if only video or image is available
else if($col1){
if(!empty($a->video)) {
echo '
<div class="col-12">
<div class="col-content wow animate__animated animate__fadeIn">
<iframe width="100%" style="min-height:'.$a->videoheight.'px;" src="'.$a->video.'?rel=0&modestbranding=1" frameborder="0" allowfullscreen=""></iframe>
</div>
</div>';
}
else if(!empty($a->image) && file_exists($_SERVER['DOCUMENT_ROOT']."/da/uploads/".$sub."/section/".$a->image)) {
echo '
<div class="col-12">
<div class="col-content wow animate__animated animate__fadeIn">
<img class="" src="'. base_url() .'da/uploads/'. $sub .'/section/'. $a->image .'" alt="'. $a->title .'" title="'. $a->title .'">
</div>
</div>';
}
}
// if only paragraph is available
else if($col2){
echo'
<div class="col-12">
<div class="col-content text-center wow animate__animated animate__fadeIn">';
echo'
'. $this->customlib->cleanTable(nl2br(htmlspecialchars_decode($a->para))) .'
</div>
</div>';
}
echo'
</div>';
if(isset($a->attachments) && !empty($a->attachments)) {
echo'
<div class="row mt-5">
<div class="col-12 text-center">';
foreach($a->attachments as $attachment) {
echo'
<a href="'.base_url().'da/uploads/'.$sub.'/attachments/'.$attachment->filename.'" download class="product-attachment my-2">
<i class="fa fa-download" aria-hidden="true"></i>
'.$attachment->title.'
</a>';
}
echo'
</div>
</div>
<!-- product attachment -->';
}
echo'
</div>
</div>
<!-- Master Row -->';
//Applying sub-sections
PHP Include Files
if you feel yourself repeating, then you can create another file and store a piece of code there, wherever you need it, import that file using include(). for more details , i would like to take a look on this
http://www.phpknowhow.com/basics/include-files/
I never had this problem before, but now working with PHP when I try to edit the content of a div with the id of a product taken directly from it's id in the database like this (both separaed in two foreach getting their current correct IDs) because I need them separated so when I can change the content, I can modify it so I can make the second DIV display: none by default and after clicking the first one making it display: inline:
<div id="h<?php echo $obra['id'] ?>" onClick="display()"> </div> // Getting ID h + 84 (h84) this time
<div id="<?php echo $obra['id'] ?>"> TEST TEXT</div> // Getting ID 84 this time)
And the function is:
function display() {
var result = document.getElementById("84").innerHTML;
result.innerHTML = "test";
alert(result);
}
Now, when I click the first DIV, it should get the content of the div with ID 84, which is "TEST TEXT", and then change it for "test" and change the content which I see in the browser and after that, alert with the new result value, but the content doesn't change and the alert shows me TEST TEXT.
Here is the full relevant code if needed:
<div class="row m-0">
<div class="accordion pl-0 col-4 text-center">
<?php if ( count($cuadros) == 0) { ?>
<p class="text-center mt-3">No hay cuadros registrados.</p>
<?php } else {
$cont = 0;
foreach ( $cuadros as $obra ) { ?>
<div class="card border-top-0 border-left-0 rounded-0 p-0">
<div class="card-header border-0" id="h<?php echo $obra['id'] /* it gets value "84" */ ?>" onClick="display()">
<h5 class="mb-0">
<?php echo $obra['nombreObras']; ?>
</h5>
</div>
</div>
<?php $cont++; } ?>
</div>
<?php foreach ( $cuadros as $obra ) { ?>
<div class="col-4 hidden" id="<?php echo $obra['id'] /* It gets value "84" */ ?>">
TEST TEXT
</div>
<?php } ?>
<?php } ?>
</div>
And a screenshot of what happens (note that the change should be reflected in the alert, which is not)
Thank you!
You are performing innerHTML agin. So it will return error. Remove innerHTML from result
function display() {
var result = document.getElementById("84");
result.innerHTML = "test";
alert(result);
}
I'm creating a website for a client, but I'm primarily a front-end developer. I had to create a while loop (which works just fine) to build a gallery. The client wants a before/after display on the gallery. I elected to use the TwentyTwo jQuery plugin. However, I am having an issue. It is only displaying the first container, which displays just fine.
The necessary jQuery, inline , and css files are displayed on that page linked above. I am using bootstrap as a framework. Here is my code:
$(window).load(function() {
$("#container1").twentytwenty();
});
<div class="row">
<div class="col-lg-12">
<h2><span class="color">Our Gallery</span> </h2>
<?php
//Selects all images
$sql = $GLOBALS['gmysqli']->query("SELECT image FROM gallery ORDER BY postDate DESC") or die($GLOBALS['gmysqli']->error);
while ($row = $sql->fetch_assoc()) {
$image = $row["image"];
?>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<div id="container1" class="twentytwenty-container">
<img src="<?php echo $beforeimage; ?>">
<img src="<?php echo $afterimage; ?>">
</div>
</div>
<?php } ?>
</div>
</div>
The problem here is the duplicate ID you generating in the php loop. This results in invalid html and can cause problems when using it as a selector.
You can switch to using a class selector:
$(document).ready(function(){
$(".twentytwenty-container").twentytwenty();
});
I updated your ready handler to the recommend structure. Or for the shorthand:
$(function() {
$(".twentytwenty-container").twentytwenty();
});
When using the class selector you can get rid of the ID in the HTML element
If you want to stick to the ID you can add a iteration variable to your loop and use the attribute selector:
$(function() {
$( "div[id^='container-']" ).twentytwenty();
});
<?php
$i = 0;
while($row = $sql->fetch_assoc()) {
$image = $row["image"]; ?>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<div id="container-<?php echo $i; ?>" class="twentytwenty-container">
<img src="<?php echo $beforeimage; ?>">
<img src="<?php echo $afterimage; ?>">
</div>
</div>
<?php
$i++;
} ?>
try without order by statement.
Example:
<div class="row">
<div class="col-lg-12">
<h2><span class="color">Our Gallery</span> </h2>
<?php
//Selects all images
$sql = $GLOBALS['gmysqli']->query("SELECT image FROM gallery") or die($GLOBALS['gmysqli']->error);
while($row = $sql->fetch_assoc())
{ $image = $row["image"]; ?>
<div class="col-lg-3 col-md-4 col-xs-6 thumb">
<div id="container1" class="twentytwenty-container">
<img src="<?php echo $beforeimage; ?>">
<img src="<?php echo $afterimage; ?>">
</div>
</div>
<?php } ?>
</div>
</div>
If you could share how you database are filled out could more easy to help you.
And the project link.
I hope helped you out anyway.
I have button that displays a modal which contains many icons, and I want it when I click one of the images it will indicate that I have clicked it. But I don't have any idea how to implement it.
So far this is how my modal looks like.
My objective:To put an indicator that I have clicked it.
CODE
<div class="modal-body">
<div class="row">
<div class="col-lg-6 pull-left">
<?php
$tokenSql = mysql_query(" SELECT * FROM topplayer WHERE user_id = '$user_id' ");
$retToken = mysql_fetch_assoc($tokenSql);
$token = $retToken['token'];
echo ("<b>Tokens : $token </b><br>");
?>
</div>
<div class="col-lg-6 pull-right">
</div>
</div>
<div class="row ml">
<?php
$sendGiftSql = mysql_query("SELECT * FROM gifts WHERE isDelete = 'false' ORDER BY price ");
while($sendGift = mysql_fetch_assoc($sendGiftSql)){
$giftIMG = $sendGift['img_path'];
echo("
<div class='col-xs-4 mb'>
<br>
<img id='edgiftPhoto' class='center-block' alt='No image' src='$giftIMG' style='height:120px; width: 120px'/>
</div>
");
}
?>
</div>
Generic, super super super simple solution. No need for a plugin.
JS:
$('.modal-body').on('click','img',function(){
$(this).toggleClass('clicked');
})
CSS:
.clicked{
border:1px solid black;
//style it however you want
}
I have the following jQuery code below:
My Html:
<div class="input-group top_buffer_small">
<label class="col-md-3 col-sm-3 text_right top_buffer_mini">Available Colors:</label>
<div class="col-md-9 col-sm-9 text_right">
<table id="availColors" align="center">
<?php
//instantiate color class
$colors = $Item->getColors();
$colorCount = $Item->getColorCount();
if($colorCount > 0){
//create a mod since we only want to show 4 colors per row.
$remainder = $colorCount%4;
$x=0; //counter variable
if(is_array($colors)){
foreach ($colors as $key=>$value){
foreach ($value as $color) {
if($remainder == 0){
//if we are at 0, make a new row
echo "<tr>";
}
//print_r($Item->getProductVariations($color));
?>
<td style="background-color:#<?php echo $color;?>" data-pictures="<?php echo htmlspecialchars(json_encode($Item->getProductVariations($color))); ?>" data-directory="<?php echo $pictures.$category.'/'.$itemid.'_'.$itemName.'/';?>"></td>
<?php
if($remainder == 3){
//end the row
echo "</tr>";
}
//$x++;
}
}
}
}
?>
</table>
</div>
</div>
Basically, I am trying to get the array values which are being passed from the to my javascript. After I get the values, I am trying to make all the image thumbnails change to the pictures on click of a color.
This is the div I am aiming to change the picture thumbnails:
<div class="row">
<div class="featured_container_small" id="productThumbnails">
<h5>Other Views</h5>
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
<!-- <div class="col-md-3 buffer_bottom"><img src="<?php echo $pictures.$category.'/'.$itemid.'_'.$itemName.'/'.$smallimage1?>" class=" center_image responsive_image"></div> -->
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
<div class="col-md-3 buffer_bottom"><img src="http://placehold.it/80x100" alt="" class=" center_image responsive_image"></div>
</div>
<div class="row">
<div class="col-md-12"><nbsp></nbsp></div>
</div>
<div class="clear"></div>
</div>
Then this is my jquery:
$(function(){
$("#availColors td").click(function(){
var imageDirectory = $(this).attr('data-directory');
var pictures = $(this).attr('data-pictures');
var pictureArray = JSON.parse(pictures);
var productThumbnails = $("#productThumbnails img");
var thumbnailCount = productThumbnails.length;
var keys = Object.keys(pictureArray);
var pic = "";
var src="";
for (var i = 0; i < keys.length; i++) {
pic = pictureArray[keys[i]];
productThumbnails[i].attr("src",imageDirectory+pic+".jpg");
}
});
});
When I perform my click function, an error returns saying "undefined is not a function".
I don't know why its doing this. Some help please.
When you iterate over the images collection, productThumbnails[i] returns the underlying HTMLImageElement which doesn't provide the attr() method. Try to wrap it with jQuery instead:
$(productThumbnails[i]).attr("src",imageDirectory+pic+".jpg");
Also, when using jQuery, the best way to access arbitrary data associated with your DOM elements is using the data() method:
var imageDirectory = $(this).data('directory');
var pictures = $(this).data('pictures');
As a bonus, you'll also get JSON deserialization out of the box and there's no need for JSON.parse():
var pictureArray = $(this).data('pictures');