Dynamic HTML page with PHP that has 12 images in first load and theres load more button to load another 12 image on click event,
Now the idea of this code to reduce page load time, So every things is going well but i have event onclick for each image loaded in this html page now how i can append new 12 images over the first 12 and so on and keep the event foreach image still running
here's the code i use ,
php to get first 12 images
$results_per_page = 12;
$page = 1;
$start = ($page-1)*12;
$data['styles'] = $this->Discover_model->get_more_styles($start);
html handling images as
<div class="product-list grid column3-4-wrap" id="interiors_samples" >
<?php if($styles):?>
<?php foreach ($styles as $style) {?>
<div class="img_card col">
<div class="sampleFind">
<img class = "Int_img" id="<?php echo $style->id?>" src="<?php echo base_url();?>include/int_imgs/ <?php echo $style->img_name;?>" alt="product-image">
</div>
</div>
<?php }?>
<?php endif;?>
</div>
jquery function to load more images over firs image
$('#load').click(function(){
var click_time = 0;
if(click_time === 0){
var page = 2;
}
click_time++;
$.ajax({
type:'POST',
data:{pagenum:page},
url:'<?php echo base_url(); ?>Process/getInterImgs',
success:function(data) {
$('#interiors_samples').append(data);
page = page + 1;
}
});
});
And this function get another 12 of images and return result to post call above
public function getInterImgs() {
$page = $_POST['pagenum'];
$this->load->model('Discover_model');
$results_per_page = 12;
$start = ($page-1)*$results_per_page;
$data['styles'] = $this->Discover_model->get_more_styles($start);
$styles = $data['styles'];
foreach ($styles as $style ){
$loadimgs = '<div class="img_card col">
<div class="sampleFind">
<img class = "Int_img" id="'.$style->id.'" src="'.base_url().'include/int_imgs/ '.$style->img_name.'" alt="product-image">
</div>
</div>';
}
print_r($loadimgs);exit();
return $loadimgs;
}
Now i need to know what is happened after append images to html Dom because the jquery method for each image works fine for first 12 images and doesn't work for loaded image known the id's name is the same with first 12 item
Any help please
Try this :
$(document).on("click", "#load", function () {
// your code
})
Related
I have two files home.php and calc.php, the file calc.php has variables parsing from XML URL and this url data keep changing automatically but the problem is i need a specific element in this home.php keep refreshing automatically
as you see in my code there is a div has alink inside it and the link has php variable $amount and this var keep updating,
so i tried to use AJAX like this but it did not work and after 1 s the link disapear So what to do please?
THANKS
var auto_refresh = setInterval(
function () {
$('#low2z3').load('calc.php'});
}, 1000);
<div id="linnnez4" class="linnne res1"><a id="low2z3"><?php echo $amount1;?></a> </div>
<!--in calc.php-->
<?php
$url = 'http://magneticexchange.com/export.xml';
$xml = simplexml_load_file($url);
foreach($xml->item as $item) {
if($item->from == "PRUSD" && $item->to == "NTLRUSD") {
$give = $item->in;
$get = $item->out;
$amount = 10;
$give1 = $amount." ".$item->from;
$get1 = $amount * $get / $give;
$get2 = number_format($get1, 2). " ".$item->to;
$amount1 = $item->amount;
break;
}
}
?>
I have undercome a problem when implementing a "Show more button"
The page will initially display 5 rows of data, then on click the button will make a call to a php function through ajax and load more results, ultimately displaying them on the page. It does this very well.
The problem is that each of the divs are clickable in their own right to allow for user interaction. Before clicking the button the first 5 are clickable and work correctly, however after loading the first 10, the first 5 become unclickable and the rest work as expected.
See my code here:
HTML:
<div class="col-sm-12 col-xs-12 text-center pushDown">
<div id="initDisplay">
<?php
// Display all subjects
echo displaySubjects($limit);
?>
</div>
<div id="show_result"></div>
<button id="show_more" class="text-center pushDown btn btn-success">Show More</button>
</div>
On click of the button the following is happening:
JQuery:
<script>
$("#show_more").on("click", function() {
$("#initDisplay").fadeOut();
});
/* This bit is irrelevant for this question
$("#addBtn").on("click", function(){
addSubject();
});
*/
var stag = 5;
$("#show_more").on("click", function(){
stag+=5;
console.log(stag);
$.ajax({
dataType: "HTML",
type: "GET",
url: "../ajax/admin/loadSubjects.php?show="+stag,
success: function(result){
$("#show_result").html(result);
$("#show_result").slideDown();
}
});
var totalUsers = "<?php echo $total; ?>";
if(stag > totalUsers) {
$("#show_more").fadeOut();
}
});
</script>
My PHP page and functions are here:
<?php
include_once '../../functions/linkAll.inc.php';
$limit = filter_input(INPUT_GET, "show");
if (isset($limit)) {
echo displayUsers($limit);
} else {
header("Location: ../../dashboard");
}
function displaySubjects($limit) {
$connect = db();
$stmt = $connect->prepare("SELECT * FROM Courses LIMIT $limit");
$result = "";
if ($stmt->execute()) {
$results = $stmt->get_result();
while($row = $results->fetch_assoc()){
$id = $row['ID'];
$name = $row['Name'];
$image = $row['image'];
if($image === ""){
$image = "subjectPlaceholder.png"; // fail safe for older accounts with no images
}
$result .=
"
<div class='img-container' id='editSubject-$id'>
<img class='miniProfileImage' src='../images/subjects/$image'>
<div class='middle' id='editSubject-$id'><p class='middleText'>$name</p></div>
</div>
";
$result .= "<script>editSubjectRequest($id)</script>";
}
}
$stmt->close();
return $result;
}
The script being called through this is:
function editSubjectRequest(id) {
$("#editSubject-"+id).click(function(e) {
e.preventDefault(); // Prevent HREF
console.log("You clicked on " + id);
$("#spinner").show(); // Show spinner
$(".dashContent").html(""); // Empty content container
setTimeout(function() {
$.ajax({ // Perform Ajax function
url: "../ajax/admin/editSubjects.php?subjectID="+id,
dataType: "HTML",
type: "POST",
success: function (result) {
$("#spinner").hide();
$(".dashContent").html(result);
}
});
}, 1500); // Delay this for 1.5secs
});
}
This will then take the user to a specific page depending on the subject which they clicked on.
Your problem is duplicate ids. First five items are present on the page always. But when you load more, you are loading not new items, but all, including first five. As they are already present on the page, their duplicates are not clickable. The original items are however clickable, but they are hidden.
Here is what you need:
$("#show_more").on("click", function(){
$("#initDisplay").html("");
});
Don't just fadeOut make sure to actually delete that content.
This is the easiest way to solve your issue with minimum changes. But better option would be to rewrite your php, so it would load only new items (using WHERE id > $idOfLastItem condition).
Also you don't need that script to be attached to every div. Use common handler for all divs at once.
$("body").on("click", "div.img-container", function() {
var id = $(this).attr("id").split("-")[1];
});
When you are updating a DOM dynamically you need to bind the click event on dynamically added elements. To achieve this change your script from
$("#editSubject-"+id).click(function(e) {
To
$(document).on("click","#editSubject-"+id,function(e) {
This will bind click event on each and every div including dynamically added div.
I have this ajax request code
function hehe2(){
var a = $(".film2numb").val();
return $.ajax({
type : "GET",
url : "php/controller1.php?page=semuafilm",
data : "data="+a,
cache: false,
success: function(data){
$('.semuafilm').load('php/film.php');
},
});
}
and it requests this php code, basically it prints out HTML data from SQL
<?php
$indicator = $_SESSION['p'];
if ($indicator == 'filmbaru') {
# code...
$batas = $_SESSION['a'];
if (!$batas) {
$batas = 1;
}
if ($batas>1) {
$batas = $batas * 8;
}
include('connect.php');
$queryfilm = "select * from tb_film order by film_year desc, film_id desc limit $batas ,8";
$exec = $conn->query($queryfilm);
while ( $f = $exec->fetch_assoc()) {
$tn = str_replace(" ","-",$f['film_name']) ;
?>
<div class='col l3 m3 s6 itemovie'><div><img src="images/dum.jpg" class="lazy" data-original='http://www.bolehnonton.com/images/logo/<?php echo $f["film_logo"]; ?>' width="214" height="317"><div><div><div><p><b><?php echo $f['film_name']; ?></b></p><p>IMDB Rating</p><p><?php echo $f['film_genre']; ?></p><p class='center-align linkmov'><a class='dpinblock browntex' href='?page=movie&filmname=<?php echo $tn; ?>'>PLAY MOVIE</a></p><p class='center-align linkmov'><a class='dpinblock' href=''>SEE TRAILER</a></p></div></div></div></div></div>
<?php
}
?>
and here is the controller
<?php
session_start();
$a = $_GET['data'];
$p = $_GET['page'];
$g = $_GET['genre'];
$_SESSION['a'] = $a;
$_SESSION['p'] = $p;
$_SESSION['g'] = $g;
?>
My question is why every time I click button that binded to the hehe2() function (4-5 times, which requested a lot of images) the page get heavier as I click incrementally(laggy, slow to scroll), is there a way to make it lighter, or is there a way to not store image cache on page or clear every time I click the button that binded to hehe2() function?
I am not sure that my advice will be helpful, I will just share my experience.
First of all you should check your binding. Do you bind click trigger only once?
Sometimes function binds multiple times and it can slow down the page.
You can put code below inside function and check the console
console.log("Function called");
If everything is fine from that point and function fires only once - I would recommend you to change flow a little bit. Is it possible to avoid many clicks in a row? If it is not big deal - you can disable button on click, show loader and enable button when AJAX request is completed. This approach will prevent from making multiple requests at once at page will be faster.
I'm making a vote system thats using images and whenever you click one of the images, it will submit that one, and then it fades out and reloads it using a php page. Problem is, the first submit works, but once it reloads, clicking on the images does nothing. Not even an alert which I've tested.
vote.js
$('.firstDisplay').on("click", function () {
alert("work1");
var win = $(this).attr("title");
var loss = $('.secondDisplay').attr("title");
send_vote(win, loss);
console.log("<-CLIENT-> Click: Sent vote");
});
$('.secondDisplay').on("click", function () {
alert("work2");
var win = $(this).attr("title");
var loss = $('.firstDisplay').attr("title");
send_vote(win, loss);
console.log("<-CLIENT-> Click: Sent vote");
});
function send_vote(win, lose) {
var data = {'win': win, 'lose': lose};
$.ajax({
type: "POST",
url: 'actions/send-vote.php',
data: data,
success: function (html) {
$('#sent-vote').css('display', 'block');
$('#sent-vote').fadeOut(2000);
$('.imageBtn').fadeOut(2000);
$('#imageDisplay').load("source/templates/vote.php");
console.log("<-SYSTEM-> Ajax request sent and processed.");
},
error: function(e) {
$('#fail-vote').css('display', 'block');
$('#fail-vote').fadeOut(2000);
console.log("<-SYSTEM-> Ajax request failed to process.");
}
});
}
vote.php
<?php
$maximumPersons = 95;
$firstDisplay = rand(1, $maximumPersons);
$secondDisplay = rand(1, $maximumPersons);
function getScore($photo_id) {
$query = "SELECT *
FROM photo_scores
WHERE photo_id='".$photo_id."'";
$result = $database->query_select($query);
return $result;
}
?>
<a href="javascript:void(0);" class="imageBtn" id="firstDisplay" title="<?php echo $firstDisplay; ?>">
<img src="<?php echo $baseURL; ?>/images/persons/<?php echo $firstDisplay; ?>.png" />
<?php // $scoreFD = getScore($firstDisplay); echo "Wins: ".$scoreFD["wins"]." Losses: ".$scoreFD["losses"].""; ?>
</a>
<a href="javascript:void(0);" class="imageBtn" id="secondDisplay" title="<?php echo $secondDisplay; ?>">
<img src="<?php echo $baseURL; ?>/images/persons/<?php echo $secondDisplay; ?>.png" />
<?php // $scoreSD = getScore($secondDisplay); echo "Wins: ".$scoreSD["wins"]." Losses: ".$scoreSD["losses"].""; ?>
</a>
it's all loading correctly, just the img/buttons wont submit/work after its reloaded.
You need to use the form $(document).on('event', '.selector', function(){}); to listen for new elements on the DOM and attach your handler to them.
The answer here is event delegation.
Binding an event listener to an object will not bind it to all other dynamically loaded or created objects, or adding the(lets say class as in your example) to another object will not apply its event listeners , since they did not exists when the script was run
$('.firstDisplay').on("click", function () {
you say all current elements with firstDisplay class do something on click. If you then add a new .firstDisplay, it wont know that it needs to listen to the on click. in short the listener is not attached on the class itself, but on the elements that have the class when the script is run.
now to get it to work, we will use event delegation
$(document).on("click",'.firstDisplay', function () {
this time around we bind the event on document. we also tell the event that should it find a firstdisplay class on an element clicked inside the document, the following function must be executed. So if new element are added, the event, bound to document now, will properly fire
I have created an rotating image banner module for an in house CMS. I did not write all the jquery for this and that's why I'm a little confused.
Basically the problem is the first image displayed in the banner after a page reload does not fade out like the rest of the images do. I understand that this probably because it is the default image loaded and is not part of the loop that's causing the image banner to rotate. The banner can be seen here: http://www.easyspacedesign.com/craig/dentalwise/
Notice how the first image after a reload sort just jumps to the next image but then all he images afterwards smoothly fade in and out.
How do I grab that first image after a reload and make it fadeout like rest?
here is the code:
<script type="text/javascript">
<!--
var doLooop = true;
$(document).ready(function(){
setInterval("loop()",5000);
});
function loop(){
if(!doLooop){ return; }
var $total = parseInt($("input[name=total_slides]").val());
var $id = parseInt($("a._active").attr("rel"));
var $new = $id+1;
if($new>$total){$new=1;}
changeSlide($new);
}
function changeSlide($id){
// Prepare selectors
var $total = $("input[name=total_slides]").val();
var $txtSlt = "#_slideText_"+$id;
var $imgSlt = "#_slideImg_"+$id;
var $active = $("a._active").attr("id");
var $new_img_href = "#animation_selectors a:nth-child("+$id+") img";
var $new_active = "#animation_selectors a:nth-child("+$id+")";
// Hide active images and text
$(".slideImg").css("display","none");
$(".slideTxt").css("display","none");
// Display selected images and text
$($txtSlt).fadeIn(1200);
$($imgSlt).fadeIn(1200);
$($txtSlt).delay(2500).fadeOut(1200);
$($imgSlt).delay(2500).fadeOut(1200);
// Update active anchor image
$("a._active img").attr("src","<?php echo ROOT; ?>Images/StyleImages/off.png");
$("a._active").removeClass("_active");
$($new_img_href).attr("src","<?php echo ROOT; ?>Images/StyleImages/on.png");
$($new_active).addClass("_active");
}
$(function(){
$("#animation_selectors a").click(function(e){
e.preventDefault();
var $id = $(this).attr("rel");
doLooop = false;
changeSlide($id);
});
});
-->
</script>
<div id="animation">
<div id="animation_slides">
<?php
$img_sql = "SELECT strImageUrl FROM tbl_mod_Animation ORDER BY intAnimationID";
if($img = $db->get_results($img_sql)){ $i=1;
foreach($img as $img){
if($i!=1){ $display = " style=\"display:none;\""; } else { $display = ""; }
echo "<div id=\"_slideImg_$i\" class=\"slideImg\" $display><img src=\"".ROOT."Images/Uploads/Slides/".$img->strImageUrl."\" alt=\"\" /></div>";
$i++;
}
}
?>
</div>
<div id="animation_text">
<?php
$text_sql = "SELECT strText FROM tbl_mod_Animation ORDER BY intAnimationID";
if($text = $db->get_results($text_sql)){ $i=1;
foreach($text as $text){
if($i!=1){ $display = " style=\"display:none;\""; } else { $display = ""; }
echo "<div id=\"_slideText_$i\" class=\"slideTxt\" $display>".$text->strText."</div>";
$i++;
}
}
?>
</div>
<div id="animation_selectors">
<?php
for($x=1;$x<$i;$x++){
if($x==1){
?><a id="slide_opt<?php echo $x; ?>" href="#" rel="<?php echo $x; ?>" class="_active"><img class="slideOpt" src="<?php echo ROOT; ?>Images/StyleImages/on.png" alt="" /></a><?php
} else {
?><a id="slide_opt<?php echo $x; ?>" href="#" rel="<?php echo $x; ?>"><img class="slideOpt" src="<?php echo ROOT; ?>Images/StyleImages/off.png" alt="" /></a><?php
}
}
echo "<input type=\"hidden\" name=\"total_slides\" value=\"".($i-1)."\" />";
?>
</div>
</div><!--end of animation-->
<?php
?>
changeSlide() sets up each slide to fade in and then fade out in 2.5 seconds. loop() calls changeSlide() every 5 seconds and passes the id of the next slide to be shown. The problem is that the first slide isn't set up the same way on page reload. It's probably just statically written on the page with the _active class.
You'd be better off, instead of setting a delay to fade each slide out after 2.5 seconds, to pass in both the previous and next slide to the changeSlide function and then fade out the previous and fade in the next.
function loop() {
...
changeSlide($id, $new);
}
and then in changeSlide:
function changeSlide($prev, $next) {
...
var $prevTxtSlt = "#_slideText_" + $prev;
var $prevImgSlt = "#_slideImg_" + $prev;
var $nextTxtSlt = "#_slideText_" + $prev;
var $nextImgSlt = "#_slideImg_" + $prev;
...
$($prevTxtSlt).fadeOut(1200);
$($prevImgSlt).fadeOut(1200);
$($nextTxtSlt).fadeIn(1200);
$($nextImgSlt).fadeIn(1200);
}