Jquery infinite scroll double print - javascript

So I've researched over and over to try and eliminate this issue to no avail. I'm a relative Noob to Javascript. The issue I'm having is that when the event handler triggers, it prints out the new 20 items I desire, but also the previous 20 then freezes after a one time load.
Any help is greatly appreciated
Here's the code:
JAVASCRIPT FUNCTION:
<script type="text/javascript">
$(window).scroll(function(){
if($(window).scrollTop() == $(document).height() - $(window).height()){
$('div#loadMoreComments').show();
$.ajax({
url: "loadeR.php?lastComment=" + $(".postedComment:last").attr("id"),
success: function(html){
if(html){
$("div#postedComments").append(html);
$("div#loadMoreComments").hide();
}else{
$("div#loadMoreComments").replaceWith("Showing All Comments!");
}
}
});
}
});
</script>
APPEND PAGE PHP:
if($_GET['lastComment']){
$NewAll = mysql_query('select*from scroll WHERE id < "'.$_GET['lastComment'].'" ORDER BY id DESC LIMIT 0,20');
$a = mysql_num_rows($NewAll);
for($i=0;$i<$a;$i++){
$id = mysql_result($NewAll,$i,'id');
$name = mysql_result($NewAll,$i,'name');
$text = mysql_result($NewAll,$i,'text');
echo "
<div class='postedComment' id='$id postedComment'>
<img src='prime1.jpg' id='userimage'/>
<div id='rightcontainer'>
<div id='walluser'>User Name $id</div>
<div id='wallcontent'>Comment/Content $name</div>
<div id='walltime'>Time posted $text</div>
</div>
</div>
";
}
}
INITIAL DIV LOADED
<div id="postedComments">
<?php
$All = mysql_query('select*from scroll ORDER BY id DESC LIMIT 0,20');
//SELECT * FROM [insert table name] ORDER BY [insert unique counter] DESC LIMIT 0,[MAX #]
$a = mysql_num_rows($All);
for($i=0;$i<$a;$i++){
$id = mysql_result($All,$i,'id');
$name = mysql_result($All,$i,'name');
$text = mysql_result($All,$i,'text');
echo "
<div class='postedComment' id='$id postedComment'>
<img src='prime1.jpg' id='userimage'/>
<div id='rightcontainer'>
<div id='walluser'>User Name $id</div>
<div id='wallcontent'>Comment/Content $name</div>
<div id='walltime'>Time posted $text</div>
</div>
</div>
";
}
?>
</div>
<div id='loadMoreComments' style="display:none;"><img src="js/loadwheel.gif"/></div>

Related

Unset img src if no url is provided vue.js

I'm learning vue.js
I'm testing how it works with ajax and the wp rest api, I'm creating a custom panel theme and I want to show the content on the right side of the screen in a scrollable panel and the pages on the left side of . the screen without the possibility to scroll.
I'm able to display the content of the posts and pages, I'm getting also the featured image, and I placed it inside an <img> tag. I need to understand how to tell vue.js that if there isn't any url data to show the featured image, the src of the image element needs to be unset. Is this possible ?
<?php get_header(); ?>
<div class="container-fluid content-wrapper" style="overflow:hidden;height:100vh;">
<div class="row" id="app" style="margin:2em 0 2em 0;">
<!-- Sidebar Top Area -->
<div class="col-sm-12 col-md-4 col-lg-4" id="navPanel" style="padding:2em;">
<?php $links = new WP_Query( array('post_type' => 'page', 'posts_per_page' => -1) ); ?>
<?php if( $links->have_posts() ): while( $links->have_posts() ): $links->the_post(); ?>
<h1 class="home-claim" style="font-size:2em;">
<a class="" href="#" v-on:click.prevent="getContent(<?php echo get_the_ID(); ?>)" ><?php the_title(); ?></a>
</h1>
<?php endwhile; ?>
<?php endif; wp_reset_postdata(); ?>
</div>
<!-- Post/Pages Content -->
<div class="col-sm-12 col-md-8 col-lg-8" id="contentPanel" style="padding:0 0 2em 0;overflow:auto;height:100vh;">
<!-- Image here -->
<img class="img-fluid w-100" v-if="featuredImage" v-bind:src="featuredImage" />
<div class="" id="" v-html="content"></div>
</div>
<!-- Sidebar Bottom Area -->
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script>
(function($){
$(document).ready(function(){
var app = new Vue({
el: '#app',
data: {
content: null,
featuredImage: null,
},
mounted: function(){
},
methods: {
getContent: function(id){
console.log('method Fired!');
var self = this;
console.log(id);
var url = 'wp-json/wp/v2/pages/'+id+'?_embed';
$.getJSON( url, function(data){
console.log(data);
self.content = data.content.rendered;
self.featuredImage = data._embedded["wp:featuredmedia"][0].source_url;
//console.log(data._embedded["wp:featuredmedia"][0].source_url);
//console.log(data.content.rendered);
});
}
}
});
}); // doc ready
}(jQuery));
</script>
<?php get_footer(); ?>
I've also noticed that only for a page I have, the wp api will return a 401 code for the featured image.
Any help will be appreciated.
Unset the featuredImage before doing the load:
(function($){
$(document).ready(function(){
var app = new Vue({
methods: {
getContent: function(id){
var self = this;
// unset the image before you are loading.
// this way it will also unset when the loading fails.
self.featuredImage = null;
var url = 'wp-json/wp/v2/pages/'+id+'?_embed';
$.getJSON( url, function(data){
self.featuredImage = data._embedded["wp:featuredmedia"][0].source_url;
});
}
}
});
});
}(jQuery));

event.target in AJAX

Hopefully, my question is not too complicated.
function showSkills(event,str) {
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
event.target.parentElement.parentElement.parentElement.nextElementSibling.innerHTML = this.responseText;
}
};
xmlhttp.open("POST","skills.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("q=" + str);
event.target.parentElement.parentElement.parentElement.nextElementSibling.style.display = "block";
}
The block is diplayed, so the last row of code is fine, but I cannot post $q. I know where the problem is, but I don't know how to fix it:
If I put document.getElementById("skills").innerHTML = this.responseText; instead of event.target.parentElement.parentElement.parentElement.nextElementSibling.innerHTML = this.responseText; everything works fine, but only for <div id="skills'>, not for skills2 of course. I have to use this script for more div IDs (skills, skills2, skills3) separately.
My HTML:
<div class="bgimg" style="background-image:url('pic/a3.jpeg');">
<h3 onclick="displayGrow(event)">bla bla</h3>
<div id="sport" class="hide resetInput"><?php include 'sport.php'; ?></div>
<div id="skills" class="hide resetInput"><?php include 'skills.php'; ?></div>
</div><!-- end of the 1st Parallax -->
<div class="bgimg" style="background-image: url('pic/a5.jpg');">
<h3 onclick="displayGrow(event)">bla bla</h3>
<div id="sport2" class="hide resetInput"><?php include 'sport.php'; ?></div>
<div id="skills2" class="hide resetInput"><?php include 'skills.php'; ?></div>
</div><!-- end of the 2nd Parallax -->
and sport.php code:
<?php
include 'cookies.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (isset($_POST['q'])) {
$q = $_POST['q'];
}}
?>
<div class="dropdown marginTop">
<button><!-- select sport -->
<?php // "select your sport"
if (isset($q)) {
$result = mysqli_query($con, 'SELECT ' .$language. ' FROM sports WHERE name1="' .$q. '" LIMIT 1');
} else {
$result = mysqli_query($con, 'SELECT ' .$language. ' FROM page WHERE title="selSport1" LIMIT 1');
}
$row = mysqli_fetch_row($result);
print_r($row[0]);
?>
</button>
<div class="dropdown-content">
<?php // sports list
$sportlist = mysqli_query($con, 'SELECT * FROM sports WHERE title = "sports" ORDER BY ' .$language. ' ASC');
while ($row = mysqli_fetch_array($sportlist)) {
echo '
<button class = "buttonList" value="' . $row[1] . '"';?>
onclick="showSport(event, this.value); showSkills(event, this.value);"
<?php echo ' style="border:0;">' . $row[$language] . '</button>
';
}
?>
</div>
</div>
So after showSport() was invoked, the button with $q value is diplayed in sport.php. This works fine for both div IDs: sport and sport2 aswell. Another function showSkills() should open skill.php in <div id="skills"> or in <div id="skills2"> and post $q there. The section was opened, but without $q inside.
Any ideas? Would help me a lot.
event.target.parentElement.parentElement.parentElement.nextElementSibling is far too much climbing up the DOM for my taste. When I understand you right, you use the same function as a event handler for multiple elements. Why don't you just pass the ID of the particular, associated div as a parameter? I add an example below.
// Note, I do not know what your 'str' is, so here it is just 'foo'
document.getElementById('event-div-1').addEventListener('click', showSkills.bind(null, 'skills1', 'foo'));
document.getElementById('event-div-2').addEventListener('click', showSkills.bind(null, 'skills2', 'foo'));
document.getElementById('event-div-3').addEventListener('click', showSkills.bind(null, 'skills3', 'foo'));
function showSkills(skills, event, str) {
// Ajax stuff
document.getElementById(skills).style.display = 'block';
}
.skills {
display: none;
}
<div class="skills"
id="skills1">1</div>
<div class="skills"
id="skills2">2</div>
<div class="skills"
id="skills3">3</div>
<div id="event-div-1">Click me for skills 1</div>
<div id="event-div-2">Click me for skills 2</div>
<div id="event-div-3">Click me for skills 3</div>

Ajax for slideshow not working

I don't seem to understand exactly how this works. When I call the get ajax method shouldn't the index change and therefore the slide should change or am I not getting something about this.
PHP/HTML
echo "<div id='slider'>
<ul class='slides'>
<li class='slide'>
<div class='pic'>
<img src= " . $dir . $pic_array[$index] . " />
</div>
<div class='caption'>
<p id='title'>$titles[$index]</p>
<p id='des'>$descriptions[$index]</p>
</div>
<div class='next'>
<i class='fa fa-arrow-right fa-2x'></i>
</div>
<div class='previous'>
<i class='fa fa-arrow-left fa-2x'></i>
</div>
</li>";
echo "</ul>
</div>
</html>";
$conn->close();
?>
Javascript
$(function () {
var arrPix = $('#json_pics').val();
var arrPix = $.parseJSON( arrPix );
var index = 0;
var $slider = $('#slider');
var $slides = $slider.find('.slides');
var $slide = $slides.find('.slide');
var $next = $slides.find('.next');
var $previous = $slides.find('.previous');
var $caption = $slides.find('.caption');
var slide_length = $slide.length;
$slider.hover(function() {
$caption.css('opacity', '1');
$next.css('opacity', '1');
$previous.css('opacity', '1');
}, function() {
$caption.css('opacity', '0');
$next.css('opacity', '0');
$previous.css('opacity', '0');
}
);
$next.click(function() {
index++;
$.get("gallery_.php?index=" + index);
});
});
EDIT: Should I be using load instead?
In an endeavor to get you a solution that
Uses AJAX
and uses PHP,
I would suggest something like the following.
'getpic.php'
Summary: (A new file... used to simplify the process of getting a new picture.)
Description: Contains a function that generates the <img> tag and related info for the next image in your gallery.
$dir = /*whatever it is*/;
$pix_array = array("image1.jpg", "image2.png", "orWhateverElse.gif" /*etc.*/);
$descriptions = /*whatever they are*/;
$titles = /*whatever they're supposed to be*/;
function priWrap($index) {
/*
This handles the actual generating of the <img> tag as well as
the caption and such.
$index refers to a specific picture in $pix_array.
*/
global $pix_array, $dir, $titles, $descriptions;
$arr_len = count($pix_array);
if ($index < 0) {
$index = $arr_len-1;
}
else if { $index >= $arr_len) {
$index = 0;
}
echo "<div class='pic'>
<img src='" . $dir . $pic_array[$index] . "' data-ind='$index' />
</div>
<div class='caption'>
<p id='title'>" . $titles[$index] . "</p>
<p id='des'>" . $descriptions[$index] . "</p>
</div>";
}
#let's get it set up to handle AJAX calls
if (isset($_GET['index'])) {
$index = intval($_GET['index']);
priWrap($index);
}
Changes to 'gallery_.php'
The code you posted should now look like this:
require_once('getpic.php');
echo "<div id='slider'>
<ul class='slides'>
<li class='slide'>
<div id='picWrapper'>";
echo priWrap($index) . "
</div><!--End #picWrapper-->
<div class='next'>
<i class='fa fa-arrow-right fa-2x'></i>
</div>
<div class='previous'>
<i class='fa fa-arrow-left fa-2x'></i>
</div>
</li>";
echo "</ul>
</div>
</body>
</html>";
$conn->close();
?>
Your javascript needs changed, too.
var index = 0;
should be
var index = parseInt($(".pic img").attr("data-ind"));
and
$next.click(function() {
index++;
$.get("gallery_.php?index=" + index);
});
should be
$next.click(function() {
index++;
$("#picWrapper").load("getpic.php?index=" + index,
/*Add callback so that index is updated properly.*/
function () {
//update our index
index = parseInt($(".pic img").attr("data-ind"));
//show our caption stuff...
$(".caption").css('opacity', '1');
}
);
});

reload javascript code on every 10 sec

I have 3 progress bar on webpage from database data . When user click on load more 3 more progress bar get added from database data.
<div id="progressBar<?php echo $rec['cid'];?>" class="tiny-green"><div></div></div>
<!-- Some codes are here --->
...
....
.....
<?php
$prj= mysql_query("select * from campaign where uid=$uid");
$record = array();
while($row = mysql_fetch_assoc($prj)){
$record[] = $row;
}
?>
<script type="text/javascript">
<?php foreach($record as $rec){?>
progressBar(<?php $perc= $rec['value']*100/$rec['value1']; echo $perc;?>, $('#progressBar<?php echo $rec['cid'];?>'));
<?php } ?>
</script>
Below is javascript plugin
<script type="text/javascript" src="js/jquery.countdown.min.js"></script>
Now problem is when i add progress bar from load_more button(Which get data by load_more.php file and it insert it on index.php file). i can see the value but progress bar is not creating because code given above not loading after clicking on load_more.
So, i want to know is there any way i can reload that code only. So, wherever there is a progress bar control placed it get the display the bar.
update with some modifications, hope it will help you
$prj= mysql_query("select * from campaign where uid=$uid order by Closing_Date DESC Limit 0,1");
$result = array('data' => '', 'progress_bar' => array());
while($row = mysql_fetch_assoc($prj)) {
$result['data'] .= '<div class="col-sm-1 col-md-4 unique" id="'.$rec['cid'].'">
<div class="well">
<div class="media services-wrap55 wow fadeInDown">
<img class="img-responsive" src="'.$rec['poster'].'"><br>
<h4 class="media-heading">'.$rec['project_Name'].'</h4>
<p> by <i>'.$rec['user_name'].'</i></p>
<p> '.$rec['short_dis'].'</p>
<a class="" href="view_project/'.$rec['cid'].'/'.$rec['slug'].'">More ... </a>
<p>
<div id="progressBar'.$rec['cid'].'" class="tiny-green"><div></div></div>
<h6>'.($rec['view']*100/$rec['view2']).'% ( <i class="fa fa-user"></i>'.$rec['view']. ') '.$rec['view2'].' views.</h6>
</p>
<div class="counter-inner"> <div id="example1" data-countdown="'.date("m/d/Y h:i:s", strtotime($rec['Closing_Date'])).'"></div></div><p> <!-- Work on this -->
<div class="col-sm-11">
<div class="entry-meta">
<span><font color="#339933"><i class="fa fa-comment"></i> </font> '.$rec['comment'].' Comments </a></span><!-- Work on this -->
<span><font color="#339933"><i class="fa fa-thumbs-up"></i></font> '.$rec['up_count'].' </a></span>
<span><font color="#339933"><i class="fa fa-thumbs-down"></i></font> '.$rec['down_count'].' </a></span>
<span><font color="#339933"><i class="fa fa-star"></i> </font> '.$rec['fav_count'].' Fav </a></span>
</div>
</div>
</div>
</div>
</div>';
$result['progress_bar'][] = array('cid' => $rec['cid'], 'perc' => $rec['value'] * 100 / $rec['value1']);
}
$(document).ready(function() {
$('#more').click(function() {
var get_last_post_display = $('.unique-class:last').attr('id'); //get ip last <li>
$('#more').html('<img src="ajax-loader.gif"');
$.post('more_prj.php', 'last_id_post='+get_last_post_display, function(html) {
if(html.data) {
$('div').append(html.data);//$('.main-div') ?
$('#more').text('Load More Project'); //add text "Load More Post" to button again
for(i = 0; i < html.progress_bar.length; i++) {
progressBar(html.progress_bar[i]['perc'], $('#progressBar' + html.progress_bar[i]['cid']));
}
} else {
$('#more').text('No more Project to load'); // when last record add text "No more posts to load" to button.
}
}, 'json');
});
});

jQuery not working the same

I am having a problem with my website.
The padding-top of div class="row slide-content" is acting weird.
For some slides it is about 223px and for other slides it uses a different padding.
PHP
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<div class="home-slider">
<ul class="slides">
<?php while ($slide =& $loop->next()): ?>
<li>
<div class="row slide-content">
<div class="large-10 large-centered columns text-center">
<?php if ( ! empty( $slide->button ) ) : ?>
<div class="SLIDERLOGO">
<?php echo $slide->button; ?>
</div><?php endif; ?><?php if ( ! empty( $slide->ititle ) || ! empty( $slide->caption ) ) : ?>
<div class="hero-title">
<div class="large-3 columns nopad border-bottom">
</div>
<div class="large-6 columns text-center">
<?php if ( ! empty( $slide->ititle ) ) : ?>
<h4 class="text-white alt-h">
<?php echo $slide->ititle; ?></h4><?php endif; ?>
</div><?php if ( empty( $slide->ititle ) ) : ?>
<div class="large-6 columns nopad border-bottom">
</div><?php endif; ?>
<div class="large-3 columns nopad border-bottom">
</div>
<h1 class="text-white">
<?php echo $slide->caption; ?></h1>
</div><!--end of hero title-->
<?php endif; ?>
</div>
</div><img alt="<?php echo esc_attr( $slide->alt ); ?>" class=
"slider-bg" src=
"%3C?php%20echo%20esc_attr(%20$slide-%3Eimg%20);%20?%3E">
</li><?php endwhile; ?>
</ul>
</div><!--end of Home slider-->
</body>
</html>
The logo is inserted here
<?php echo $slide->button; ?>
Both logo's are exactly the same dimensions
JS
// Append HTML 's as CSS Background for slides
// also center the content of the slide
jQuery('.home-slider .slides li').each(function () {
var imgSrc = jQuery(this).children('.slider-bg').attr('src');
jQuery(this).css('background', 'url("' + imgSrc + '")');
jQuery(this).children('.slider-bg').remove();
var slideHeight = jQuery(this).height();
var contentHeight = jQuery(this).children('.slide-content').height();
var padTop = (slideHeight / 2) - (contentHeight / 2);
jQuery(this).children('.slide-content').css('padding-top', padTop);
});
It wont happen every time but sometimes the padding between the logo and the top of the page changes. I hope i have explained wel enough :)
Many thanks!
Daan
try running your code on $(window).load(function() { }); instead of at the bottom of the page, chances are if you are working with larger slide images that not all of them are fully loaded before your calculations are applying.
The new code would look like this...
jQuery(window.load(function() {
jQuery('.home-slider .slides li').each(function () {
var imgSrc = jQuery(this).children('.slider-bg').attr('src');
jQuery(this).css('background', 'url("' + imgSrc + '")');
jQuery(this).children('.slider-bg').remove();
var slideHeight = jQuery(this).height();
var contentHeight = jQuery(this).children('.slide-content').height();
var padTop = (slideHeight / 2) - (contentHeight / 2);
jQuery(this).children('.slide-content').css('padding-top', padTop);
});
});

Categories