How to separate php code from an HTML page? - javascript

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/

Related

Using a jQuery function with a PHP while loop

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.

How to make an image slider with dynamic content

How can I make a content slider, like the popular product sliders shown on most websites (Flipkart, Amazon), which scroll left and right on button click, similar to this image:
I have only four contents showing, but I want to add some more, and I want it to slide on button click. Sorry, I dont know the exact term for it.
These content values would be dynamic.
<div class="dialog">
<div class="shop_img">
<img src="../image/shops/1.jpg">
</div>
<hr id="hr">
<div class="shop_name">
<?php echo $name;?>
</div>
<a href="detail.php?add=<?php echo $add_id;?>"><div class="address">
<span id="1">ADDRESS</span><span id="2"><i class="fa fa-arrow-right" aria-hidden="true"></i></i></span>
</div></a>
</div>
This is called carousel.
You can use a javascript plugin called owl carousel from here http://www.owlcarousel.owlgraphic.com/ to achieve that effect.
You can use php foreach loop to dynamically generate your carousel items inside carousel container like below:
<?php
foreach ($items as $key => $item) {
ob_start();
?>
<div class="dialog">
<div class="shop_img">
<img src="../image/shops/<?php echo $item->imageName;?>">
</div>
<hr id="hr">
<div class="shop_name">
<?php echo $item->name;?>
</div>
<a href="detail.php?add=<?php echo $item->id;?>"><div class="address">
<span id="1">ADDRESS</span><span id="2"><i class="fa fa-arrow-right" aria-hidden="true"></i></i></span>
</div></a>
</div>
<?php
$itemHtml = ob_get_clean();
print $itemHtml;
}
?>

Append multiple divs at particular positions in a grid in jQuery

I am loading a grid of news stories and want to append two DFP adverts at a particular place in the grid - which is define by a data attribute data-adposition
Here's the HTML of the divs
<div class="aggregator">
<div class="news-item"> </div>
<div class="news-item"> </div>
<div class="news-item"> </div>
<div class="news-item"> </div>
</div>
<!-- AS AN EXAMPLE I WANT TO APPEND AFTER THE 2ND AND 4TH BUT THIS COULD CHANGE -->
<div class="aggregator__dfp" data-dfpcode='<?php echo $dfpCode; ?>' data-halfcode='<?php echo $dfpHalfCode; ?>'>
<div class="dfp" data-adposition="<?php echo $dfpPos; ?>">
<h2>Test DFP ONE</h2>
</div>
<div class="dfp" data-adposition="<?php echo $dfpHalfPos; ?>">
<h2>Test DFP TWO</h2>
</div>
</div>
I am then looping through and currently using detach() to preserve the data but remove it from the document.
$(".dfp").each(function(){
var dfpHTML = $(this).detach();
var dfpPos = $(this).data("adposition");
$(selector + " .news-item").eq(dfpPos).after(dfpHTML);
});
Having no luck currently! The detach() works as it stores the data when I console.log but does no append to the position defined in the data-adposition
it works for me. what are you getting back from the php expression for data-adposition?
$(document).ready(function(){
var selector = ".aggregator";
$(".dfp").each(function(){
var dfpHTML = $(this).detach();
var dfpPos = $(this).data("adposition");
$(selector + " .news-item").eq(dfpPos).after(dfpHTML);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="aggregator">
<div class="news-item">n1 </div>
<div class="news-item">n2 </div>
<div class="news-item">n3 </div>
<div class="news-item">n4 </div>
</div>
<!-- AS AN EXAMPLE I WANT TO APPEND AFTER THE 2ND AND 4TH BUT THIS COULD CHANGE -->
<div class="aggregator__dfp" data-dfpcode='<?php echo $dfpCode; ?>' data-halfcode='<?php echo $dfpHalfCode; ?>'>
<div class="dfp" data-adposition="1">
<h2>Test DFP ONE</h2>
</div>
<div class="dfp" data-adposition="2">
<h2>Test DFP TWO</h2>
</div>
</div>

mysql retrieve data, for each data append a new row

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
});
}

Webpage loading images from MySQL slowly

I am building a webpage where i am displaying about 10 photos in a slider.The photos are being fetched from a folder where it is uploaded,the code is given below.
<div class="main">
<div class="main_slider">
<div id="bg"> <img src="images/c.jpg" width="1680" height="1050" alt="Test Image 1" title="" id="bgimg" /> </div>
<div id="preloader"> <img src="images/ajax-loader_dark.gif" width="32" height="32" /> </div>
<!--<div id="img_title"></div>-->
<div id="toolbar"> <img src="images/toolbar_fs_icon.png" width="50" height="50" /> </div>
<div id="thumbnails_wrapper">
<div id="outer_container">
<div class="thumbScroller">
<div class="container">
<?php
include("connect.php");
$s=mysql_query("Select image from gallery where active_home=1 ") or die(mysql_error());
while($row=mysql_fetch_array($s))
{
$img=$row["image"];
//$image= "<img src=\"images/gallery/$img\" width=200 height=120>";
echo "<div class=content_img>";
echo "<div> <img src=\"images/gallery/$img\" height=138 width=238 alt=image class=thumb style=opacity:0.6;/> </div>";
echo " </div> ";
}
?>
</div>
</div>
</div>
</div>
<div class="clr"></div>
</div>
The page is loading very slow in the server and browser crashing frequently.I have tried reducing the image size but nothing improves.
You can clean up your code like this:
// Main PHP part
include("connect.php");
$STH = $DB->query("SELECT image FROM gallery WHERE active_home=1");
$rows = $STH->fetchAll(PDO::FETCH_ASSOC);
$images = array();
foreach ($rows as $row) {
$images[] = $row['image'];
}
// Main HTML part
?>
<div class="main">
<div class="main_slider">
<div id="bg">
<img src="images/c.jpg" width="1680" height="1050" alt="Test Image 1" title="" id="bgimg" />
</div>
<div id="preloader">
<img src="images/ajax-loader_dark.gif" width="32" height="32" />
</div>
<div id="toolbar">
<a href="#" title="Maximize" onClick="ImageViewMode('full');return false">
<img src="images/toolbar_fs_icon.png" width="50" height="50" /></a>
</div>
<div id="thumbnails_wrapper">
<div id="outer_container">
<div class="thumbScroller">
<div class="container">
<?php foreach ($images as $image) { ?>
<div class="content_img">
<div>
<a href="images/gallery/<?= $image; ?>">
<img src="images/gallery/<?= $image; ?>" height="138" width="238" alt="image" class="thumb" style="opacity:0.6;" />
</a>
</div>
</div>
<?php } ?>
</div>
</div>
</div>
</div>
<div class="clr"></div>
</div>
In that way, you have properly separated the HTML from the PHP. Now, all bugs should be more obvious and easier. You can add checks at the end of the PHP, you can forget about needing to escape the " with \" manually and your code is more focused and clean. Note that I've changed the code from mysql_ to PDO, so now it shouldn't really work (you need to create the $DB = new PDO(), normally in connect.php.
Even more, now you can test where the problem is by doing something like this:
$start = microtime(true);
include("connect.php");
$STH = $DB->query("SELECT image FROM gallery WHERE active_home=1");
$rows = $STH->fetchAll(PDO::FETCH_ASSOC);
$images = array();
foreach ($rows as $row) {
$images[] = $row['image'];
}
echo "Load time: " . (microtime(true) - $start) . "<br>";
In that way you know if it's your PHP or your HTML (check it with the browser's network profiler) what takes ages to load.
Try
Jpeg images instead of png
Save images with option "Save image for web"
You can use RIOT image optimisation tool
For reducing load time you can use CSS sprites, which are CSS codes that display a piece of a larger image. This technique is often used for mouse-over states on buttons. E.g. with a sprite you can display a piece of an image as a button on your site and display a different piece of that image as the button whenever a user mouses over the image.
Do not use an Image at all. we can generate rounded rectangles, gradients, drop shadows, and transparent images using CSS
I think you should try to store images on disk and check if images load faster from hard drive .

Categories

Resources