Ajax for slideshow not working - javascript

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

Related

Cannot set property 'onclick' of null in my function js

I have a problem. I used javascript for settings display block or display none. I get an error in the console "Uncaught TypeError: Cannot set property 'onclick' of null
at script.js?ver=1.0.0:15". I added a script tag in the header, then in the footer and still the same.
Also I added defer in my script tag and still nothing. Function it works on another site.
JS Code
var element = document.getElementById('powierzchnia');
if (element.className === 'show col-12 gallery-block grid-gallery') {
element.className = 'hide col-12 gallery-block grid-gallery';
document.getElementById('powierzchnia_chup').style.display = 'none';
document.getElementById('powierzchnia_chdown').style.display = 'inline';
} else {
element.className = 'show col-12 gallery-block grid-gallery';
document.getElementById('powierzchnia_chup').style.display = 'inline';
document.getElementById('powierzchnia_chdown').style.display = 'none';
}
}
HTML and PHP code
<div class="first-box">
<h4 id="show-powierzchnia" style="cursor: pointer;">
<span>Powierzchnia panela</span>
<span class="span-fr">
<img id="powierzchnia_chup" style="display: none;" src="<?php echo get_template_directory_uri(); ?>/img/chervon-up.svg" />
<img id="powierzchnia_chdown" src="<?php echo get_template_directory_uri(); ?>/img/chervon-down.svg" />
</span>
</h4>
</div>
<div id="powierzchnia" class="hide col-12 gallery-block grid-gallery">
<div class="row">
<?php
foreach( $media_wzory_powierzchnia as $wzory ){
echo '<div class="col-md-3 item item-custom-gallery mb-3">';
echo '<a class="lightbox" href="'.wp_get_attachment_url($wzory['zdjecie_powierzchni']).'">';
echo '<img class="img-gallery image scale-on-hover" src="'.wp_get_attachment_url($wzory['zdjecie_powierzchni']).'">';
echo '<div class="w-100 text-center">';
echo '<h5>'.$wzory['nazwa_powierzchni'].'</h5>';
echo '</div>';
echo '</a>';
echo '</div>';
}
?>
</div>
</div>
try using DOMContentLoaded event:
document.addEventListener("DOMContentLoaded", function() {
// code...
var element = document.getElementById('powierzchnia');
if (element.className === 'show col-12 gallery-block grid-gallery') {
element.className = 'hide col-12 gallery-block grid-gallery';
document.getElementById('powierzchnia_chup').style.display = 'none';
document.getElementById('powierzchnia_chdown').style.display = 'inline';
} else {
element.className = 'show col-12 gallery-block grid-gallery';
document.getElementById('powierzchnia_chup').style.display = 'inline';
document.getElementById('powierzchnia_chdown').style.display = 'none';
}
});
Now the script should run only when the Html content has been loaded :)

Limiting the number times while loop loop

<div class="teachers1">
<div class="teamySlides">
<div class="yourteachers">
<?php
while ($row = mysqli_fetch_array($query)) {
echo '<a class="teachers" href="teacherinfo.php?id=' . $row['IDNum'] . '">
<img src="pictures/blank photo.png" class="teacherpic"><br>
<span>'.$row['LastName'].'</span><br>
<span>'.$row['Grade'].' - </span>
<span>'.$row['Section'].'</span>
</a>';
}
?>
</div>
</div>
<a class="prev" onclick="tplusSlides(-1)">❮</a>
<a class="next" onclick="tplusSlides(1)">❯</a>
<div class="dot-container">
<span class="tdot" onclick="tcurrentSlide(1)"></span>
<span class="tdot" onclick="tcurrentSlide(2)"></span>
</div>
</div>
The code above is used to generate objects based on how many the data is on the database. To better understand it here is a picture of the system:
The problem is when the data exceed 8, the objects do not go to the next page. The reason is that I dont know how to do that.
For example I clicked the right arrow ">" the code must go to the second page and so on with the rest of the object.
Can anyone help me or can anyone provide me with the syntax? Thanks.
Javascript:
var ti;
var tslides = document.getElementsByClassName("yourteachers");
var tdots = document.getElementsByClassName("tdot");
if (n > tslides.length)
tslideIndex = 1
if (n < 1)
tslideIndex = tslides.length
for (ti = 0; ti < tslides.length; ti++)
tslides[ti].style.display = "none";
for (ti = 0; ti < tdots.length; ti++)
tdots[ti].className = tdots[ti].className.replace(" active", "");
tslides[tslideIndex-1].style.display = "block";
tdots[tslideIndex-1].className += " active";

Dynamically sort posts by tags into a Wordpress loop

I got a a custom loop into my Wordpress custom blog page, and Im displaying all my posts into it, like that :
<section class="container blog-article-actu">
<div class="row">
<?php
$the_query = new WP_Query('showposts=-1');
while ($the_query->have_posts()) :
$the_query->the_post();
$catObj = get_the_category();
?>
<article class="blog-article-actu-article" style="background:url('<?php $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID), 'thumbnail' ); ?><?php echo $url ?>');">
<div class="blog-article-actu-article-top">
<h2><?php the_title(); ?></h2>
<div class="details-blog-article-actu">
<div class="blog-article-actu-date">
<span class="day"><?php the_time( 'd' ) ?></span><br>
<span class="month"><?php the_time( 'F' ) ?></span>
</div>
<a href="#" target="_blank"><p>
<?php
if (($catObj[0]->name == 'Actualités et évènements') OR ($catObj[1]->name == 'Actualités et évènements')) {
echo "<img src=\"XXX/actu-icon.png\" alt=\"Actualités et évènements\">";
} elseif (($catObj[0]->name == 'Témoignages') OR ($catObj[1]->name == 'Témoignages')) {
echo "<img src=\"XXX/chat-icon.png\" alt=\"Témoignages\">";
} elseif (($catObj[0]->name == 'Vidéos') OR ($catObj[1]->name == 'Vidéos')) {
echo "<img src=\"XXX/video-icon.png\" alt=\"Vidéos\">";
} else {
echo "";
}
?>
</p></a>
</div>
</div>
<div class="blog-article-actu-article-bottom-wrap">
<span class="blog-article-actu-article-excerpt"><?php the_excerpt();?></span>
<span class="blog-article-actu-article-bottom">En savoir <span>+</span></span>
<div class="social-blog-article-actu">
<i class="fa fa-twitter" aria-hidden="true"></i>
<i class="fa fa-facebook" aria-hidden="true"></i>
</div>
</div>
</article>
<?php // End of the loop.
endwhile;
?>
</div>
</section>
Then I was asked to build something to sort them, by tags, dynamically, with a tag system like this one : https://codepen.io/Chaaampy/pen/gWOrvp
But Im a bit lost about that ... I thought about get the tags for each posts in my loop, and then add them as a CSS class, like that maybe I could show or hide some articles in JS ... Meh, I don't know, has someone got any ideas for me ?
Thanks ! :)
If anyone is interested, found a solution by building something like that : https://codepen.io/Chaaampy/pen/gWOrvp
$(function filter() {
var selectedClass = "";
$(".link").click(function(){
selectedClass = $(this).attr("data-rel");
$(".wrap").fadeTo(100, 0.1);
$(".wrap section").not("."+selectedClass).fadeOut().removeClass('scale_anm');
setTimeout(function() {
$("."+selectedClass).fadeIn().addClass('scale_anm');
$(".wrap").fadeTo(300, 1);
}, 300);
});
});
Note that I get the tags into Wordpress with get_the_tags, and then I add them as a class to the elements I want to show / hide

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>

Jquery infinite scroll double print

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>

Categories