During click of load more button, some divs become unclickable - javascript

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.

Related

Trying to dynamically add, and name, div to page using javascript/php

I am new to php and javascript. I want to dynamically add a div to a page with php. In the end what I want is to be able to call a php function that adds a div. I want to call the function multiple times for a single page - so I want to add multiple divs via multiple function calls.
That doesn't seem to be difficult, but... I want each of the dynamically added divs to have the same class name, but a unique id and, for various reasons, I want the id to be based on the number of divs of that class already on the page (e.g. the first div added might have id = 0. the second id = 1, third id = 2 etc.).
I have looked a stackoverflow but haven't found any clues. I'd really appreciate any help.
I have tried the following, but it doesn't work (this is a very simplified version):
function getCount() {
?><script>
$(document).ready(function(){
var elems = $('body').find('.mydiv');
$.ajax({
type: 'POST',
url: '',
data: {count: elems.length},
cache: false,
success: function(response) {
console.log(response);
}
});
});
</script><?
}
echo '<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="../jquery-3.2.1.js"></script>
</head>
<body>';
$count = -1;
getCount();
if (!empty($_POST)) {
foreach($_POST as $key => $value) {
if (!empty($key) && !empty($value)) {
echo 'key = '.$key.' value = '.$value;
if ($key == 'count') {
$count = $value;
}
}
}
}
if ($count > -1)
echo "<div class = 'mydiv' id = 'mydiv".$count."'></div>";
echo "</body></html>";
you dont want to mix js and php here, you can achieve this using php alone, here is the code sample
<?php
echo 'your headers and layout tags go here';
function addDiv($count){
echo "<div class = 'mydiv' id = 'mydiv".$count."'>current div id is ".$count."</div>";
}
$count=0;
addDiv($count++);
addDiv($count++);
addDiv($count++);
?>

ajax / jquery not passing 2nd click values [duplicate]

This question already has an answer here:
Function doesn't work after appending new element
(1 answer)
Closed 5 years ago.
Extremely new to JavaScript, jquery and ajax and am having difficulties with a very basic set of scripts to load more data from a database on button clicks.
The first time I click load more, it works. But the 2nd clicks do not pass the values and does nothing.
Here is the main script that loads data once and includes the jquery, ajax stuff.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn1, #btn2").click(function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
$("#btn1").hide();
$("#div1").append(response);
}
}
});
});
});
</script>
</head>
<?php
// main.php contains db connection
include('main.php');
$rowsperpage = 2;
$q = "SELECT col1, col2 from mytableORDER BY col1 LIMIT $rowsperpage OFFSET 0";
$r = pg_exec($dbconnect, $q);
echo "<div id='div1' style='margin:10px;'>";
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
echo "<button id='btn1' value=2>Load More</button>";
echo "</div>";
?>
And here is the script fetched more data to display.
<?php
include('../config.php');
include('functions.php');
$rowsperpage = 2;
if(isset($_POST['page'])) {
$paged=$_POST['page'];
} else {
$paged = 1;
}
if($paged > 1) {
$rowoffset = $rowsperpage * ($paged -1);
$limit = " LIMIT $rowsperpage OFFSET $rowoffset";
} else {
$limit = " LIMIT $rowsperpage OFFSET 0 ";
}
$q = "select subindustryid, subindustry from sub_industries ORDER BY subindustry $limit";
$r = pg_exec($dbconnect, $q);
while ($row = pg_fetch_row($r) ) {
echo "<div>$row[1]</div>";
}
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";
?>
The problem is the the 2nd button is displayed and nothing happens when it gets clicked.
Thank for your time!
The problem is the event binding. Change this line-
$("#btn1, #btn2").click(function() {
to this line
$("#div1").on("click","#btn1, #btn2",function(){
Also your php returns a button with id btn1 and not btn2
Read about jQuery Event bindings here: https://learn.jquery.com/events/handling-events/ and http://learn.jquery.com/events/event-delegation/
Actually id identifiers should be unique- this is general convention. You have load more button with id="#btn1" and hiding old button appearing new button from the response text form ajax by hiding and appending- but you can manage such with out sending button in response text-
Have following changes on your html page
value should be quoted <button id="btn1" value="2">Load More ... </button>
Make use of dedicated function calling in jQuery like- $(document).on('event','dom_identifiers',callbackfunction(){})
In ajax don't need to hide current button which is clicked, instead of hiding the button just add new records fetched before the load more button by using before() function of jQuery
For next page you can increase the value of current button
$(document).ready(function(){
// dedicated function calling
$(document).on('click','#btn1',function() {
pagenum = $(this).val();
val = "Loading page " + pagenum + "...";
$(this).text(val);
$.ajax({
type: "POST",
url: "loadmore.php",
data: {page: pagenum},
success: function(response){
if(response){
// increase the value load more
$("#btn1").val(parseInt($("#btn1").val())+1);
// add response data just before the loadmore button
$("#btn1").before(response);
}
}
});
});
});
button should be like
echo "<button id='btn1' value="2">Load More</button>";
Now in fetching php page please remove these two lines-
$nextpage = $paged + 1;
echo "<button id='btn1' value=$nextpage>Load even more </button>";

jQuery $.ajax not passing variable to PHP

I want to make a 'show more' button with jQuery AJAX. I have a button with a loaded attribute like so:
<button type="button" class="smbt btn center-block" data-loaded="3">Show More</button>
In the javascript file I wrote this:
var smbt = $(".smbt");
smbt.click(function() {
var limit = $(smbt).attr('loaded');
// alert(loaded + " picture");
$.ajax({
url: '../view/profile.php',
type: 'POST',
data: ({limit1: limit}),
success: function(result) {
console.log("success");
},
error: function() {
alert("error");
}
});
Then I try to get the limit1 variable:
$limit = $_POST["limit1"];
I read the $.ajax documentation and a lot of questions and answers, I tried a lot of way to make it work but it always gives this error:
Undefined index: limit1
Try this:
var smbt = $(".smbt");
smbt.click(function() {
var limit = $(smbt).data('loaded');
$.ajax({
url: './view/profile.php',
type: 'POST',
data: {limit1: limit},
success: function(result) {
console.log("success");
},
error: function() {
alert("error");
}
});
});
You are using data-* attribute, so to get the value, you use $.data() function: https://api.jquery.com/jquery.data/
If once someone also had this problem this is how I made it work.
So there is a profile.php which contains and shows the uploaded pictures. I want want to use a button which increase the LIMIT in sql. So the profile.php contains everything. There is a div which contains the pictures wit query result and after it have the load more button. It's looks like this:
<div class="row mg-bt-20" id="cont">
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " <div class='col-md-4 col-sm-6 mg-bt-20'>
<div class='pics' data-toggle='modal' data-id='".$row['id']."' data-target='#myModal'>
<img src='" . $row['path'] . "'>
<p class='text-center' style='line-height: 6vh;'>". $row["description"] ."</p>
</div>
</div>";
}
} else {
echo "<p style='text-align: center; color:#fff; font-size: 20px;'>No posts yet.</p>";
}
?>
</div>
The problem was I try to send the variable to this profile.php but it's not work at all. I tried everything but it's just not working. So I made a new php file called show_more.php which contains only the php query results from the code above:
<?php
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo " <div class='col-md-4 col-sm-6 mg-bt-20'>
<div class='pics' data-toggle='modal' data-id='".$row['id']."' data-target='#myModal'>
<img src='" . $row['path'] . "'>
<p class='text-center' style='line-height: 6vh;'>". $row["description"] ."</p>
</div>
</div>";
}
} else {
echo "<p style='text-align: center; color:#fff; font-size: 20px;'>No posts yet.</p>";
}
?>
So my jQuery code is:
var smbt = $(".smbt");
var limit = $(smbt).data('loaded');
smbt.on('click',function(event) {
event.preventDefault();
limit += 3;
console.log(limit);
// alert(loaded + " picture");
$.ajax({
url:"../php/show_more.php",
data: {limit1: limit},
success:function(data){
$("#cont").html(data);
}
});
This is successfully send the limit1 variable to the show_more.php.
In the show_more.php I just write $_POST["limit1"] to get the data.
And the sql query looks like this:
$sql = "SELECT * FROM images where user = '$username' ORDER BY id DESC LIMIT $limit";
So here is how it's work:
First of all when the profile.php is loaded the pictures are shows if you have one but its limited to shown only 3 at first. So after you click the load more button it runs the ajax code which increase the limit variable with 3 so we get a new number which is 6 now (I always increase with 3). The ajax code first send the data to the given url which is the show_more.php in this case. I write it in oop so I have a class which handle all the image thing and I have a function in it which show the images so i just pass a variable in it like this public function showImg($limit){...}. So here is where the magic happens. It's always change the limit number once I clicked. after when it's happened in ajax code the success part handle the result. The result will the html code which will be added to the image container.
I hope I help with this and I didn't write stupid things(also sorry for my english). It works for me in this form.
And thanks for everybody whose help.

ajax request makes page lag

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.

DIV not being created from PHP when doing AJAX call

I am trying to call a PHP script in my main PHP file.Below is the Jquery/Ajax part of the main php file. The display_stationinfo.php is supposed to create the DIVs in the main but it isnt.
this is what I tried so far, im new to Jquery and AJAX. thanks in advance!
working fiddle: http://jsfiddle.net/52n861ee/
thats what I want to do but when I click on desk_box DIV, the toggle station_info DIV is not being created by my display_stationinfo.php script.
When I view source code both DIVs are supposed to be already created but only desk_box is.. what am I doing wrong?
JQuery/AJAX part:
<div id="map_size" align="center">
<script type="text/javascript">
//Display station information in a hidden DIV that is toggled
//And call the php script that queries and returns the results LIVE
$(document).ready(function() {
$(".desk_box").click(function() {
alert("before toggle");
var id = $(this).attr("data")
alert(id);
alert($(this));
$("#station_info_"+id).toggle();
alert("after toggle");
$.ajax({
url: 'display_stationinfo.php',
type: 'GET',
success: function(result) {
alert("before result");
$("#station_info_"+id).html(result);
alert("result: " + result); //it shoes every DIV being created and not the one that I clicked on
alert("after result");
}
});//end ajax
});//end click
});//end ready
</script>
</div> <!-- end map_size -->
display_station.php (script that I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if ($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while ($row = mysqli_fetch_assoc($station_result)) {
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
$html = "<div class='station_info_' id='station_info_".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
echo $html;
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
Is fetching every row from the table coordinates, is this what you want to do? Or do you just want to return only the row with the id the users clicked?
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
success: function(result) {}
});
php
$id = $_POST['id']
"SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates WHERE coordinate_id == " $id;
Looking at you example, I would also guess that the problem could be that you are returning a string and putting it inside the target div so that the finished div looks somthing like this:
<div class="station_info_" id="station_info_84" style="position: absolute; left: 20px; top: 90px; display: block;">
<div class="station_info_" id="station_info_84" style="position:absolute;left:20px;top:90px;">
Hello the id is:84<br>
Section:Section B<br>
</div>
</div>
Instead of returning a string you could return a json object and append only data to the target div
php
while ($row = mysqli_fetch_assoc($station_result)) {
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
$result = array('id' => $id, 'x_pos' => $x_pos, 'y_pos' => $y_pos, 'sec_name' => $sec_name);
echo json_encode($array);
}
jQuery
$.ajax({
url: 'display_stationinfo.php',
data: { 'id': id },
type: 'POST',
dataType: "json",
success: function(json) {
$("#station_info_"+id)
.css({'left':json.x_pos ,'top': json.y_pos})
.append('<p>Hello the id is:'+ json.id +'</br>Section:'+ json.sec_name +'</p>');
}
});

Categories

Resources