Cannot read property 'scrollHeight' of undefined - javascript

I have developed a chat system using javascript and php but the problem is that when a new message is received or the messages are more and more and it got a scroll when new message is receive the user have to scroll custom to go to the bottom so I tried to add the javascript to make the scroll be at bottom but the thing is that it is not working and also getting a javascript error though
here is the error what i got
Uncaught TypeError: Cannot read property 'scrollHeight' of undefined
also I have placed an ajax cache false to refresh chat log every 2 seconds so that the new message can be seen not by refreshing the page by directly refreshing via jquery does it effect this?
here is my code
<div class="sidebar-content">
<?php
$get_query = mysqli_query($connection, "SELECT * FROM users WHERE uid != '".$_SESSION['uid']."'");
while($data_user = mysqli_fetch_assoc($get_query)) {
?>
<div class="contact" onclick="get(<?php echo $data_user["uid"]; ?>);">
<?php if(!empty($data_user["profile_picture"])) { ?>
<img src="<?php echo $data_user["profile_picture"]; ?>" class="contact__photo" />
<?php } else { ?>
<img src="uploads/profile_img.jpg" class="contact__photo" />
<?php } ?>
<span class="contact__name"><?php echo $data_user["fullname"]; ?></span>
<span class="chat__id"><?php echo $data_user["uid"]; ?></span>
<span class="contact__status <?php if($data_user["online_status"] == "Online") { echo "online";} ?>"></span>
</div>
<?php } ?>
<div class="search">
<img src="https://s3-us-west-2.amazonaws.com/s.cdpn.io/142996/elastic-srch.png" alt="" class="search__img" />
<input type="text" class="search__input" placeholder="Search" />
</div>
</div>
<div class="chat">
<span class="<?php if($status == "Online") { echo 'online_stat';} else {echo "ofline_stat";} ?>"></span>
<span class="chat__back" onclick="reload();"></span>
<span class="chat__status">status</span>
<div class="chat__person">
<span class="chat__online active"></span>
<span class="chat__name" id="chat_name">Huehue Huehue</span>
<span class="contact__id" id="contact__id">Huehue Huehue</span>
</div>
<div id="chat_messages">
</div>
<script>
$.ajaxSetup({cache:false});
var timeout = setInterval(reloadChat, 2000);
function reloadChat () {
var rid = document.getElementById("contact__id").innerHTML;
$('#msgs').load('includes/messages.php?receipt_id='+rid);
}
$('#chat-scroll').animate({
scrollTop: $('#msgs').get(0).scrollHeight}, 2000);
</script>
</div>

change this line
scrollTop: $('#msgs').get(0).scrollHeight}, 2000);
to
scrollTop: $('#msgs').eq(0).scrollHeight}, 2000);
or
scrollTop: $('#msgs')[0].scrollHeight}, 2000);

Related

Window on load function is not firing until i refresh page manually?

I'm showing a loading bar before the content loads successfully. And after load I am displaying the content by jQuery but when i visit the page first time the loader is showing forever and the on load event isn't firing. It fires when i manually refresh the page. What's wrong with my code?
Event call code:
$(window).on('load', function(){
$("#slider-pre-loader").fadeOut("slow");
$("#video-blog-slider").fadeIn();
});
Dynamic HTML:
<div id="slider-pre-loader"></div>
<div id="video-blog-slider" style="display: none">
<div class="blog-category-items blog-page" id="blogIndex">
<div class="container">
<?php
$hpos = 0;
foreach ($categories as $category):
$categoryhref = fakeUrl::genSlugFromText($category['name']);
$listVideos = $category['videos'];
if (in_array($category['name'], $categoryDisplay)) :
?>
<div class="blog-groups">
<div class="group-heading">
<h3>
Test title
</h3>
</div>
<?php if ($category['desc'] != '') :?>
<p class="group-desc"><?php echo $category['desc'];?></p>
<?php endif;?>
<?php
$slideClass = '';
if (!$detect->isMobile() && !$detect->isTablet() ) {
$slideClass = 'blog-slider';
}
?>
<div class="<?php echo $slideClass;?> owl-lg-dot mb-none owl-theme owl-loaded" id="videoList">
<?php
$v = 0;
foreach ($listVideos as $video) :
$v++;
$itemClass = '';
if (($detect->isMobile() || $detect->isTablet()) && $v > 5) {
$itemClass = 'item-disable';
}
$videoSlug = fakeUrl::genSlugFromText($video['title']);
?>
<div class="blog-item <?php echo $itemClass;?>">
<div class="blog-image">
<a href="/blog/<?php echo $videoSlug; ?>" title="<?php echo $video['title'];?>">
</a>
</div>
<div class="caption">
<a class="blog-list-video-title" href="/blog/<?php echo $videoSlug; ?>" title="<?php echo $video['title'];?>">
</a>
</div>
<div class="blog-metas">
<small class="blog-views"><?php echo number_format($video['views']); ?> views</small>
</div>
</div>
<?php
endforeach;
?>
</div>
</div>
<?php
endif;
endforeach;
?>
</div>
</div>
</div>
jQuery placed before event call:
<script src="//code.jquery.com/jquery-1.11.3.min.js" async></script>
Don't place async attribute on your script tags unless you really need your script file to be loaded asynchronously. Right now, your 'jQuery' code is being loaded asynchronously, i.e. jQuery is most probably not loaded when you are trying to attach your event.
The only explanation for it working the second time upon manual refresh is that the browser is 'synchronously' loading the cached resource. Different browsers do this differently, so you can expect inconsistent behaviour there.
Just remove the async attribute, and you should see your event firing every time.
The $(window) selector is for selecting the viewport whereas the $(document) selector is for the entire document (that is, what's inside the <html> tag).
Try using the following:
$(document).on('load', function(){
$("#slider-pre-loader").fadeOut("slow");
$("#video-blog-slider").fadeIn();
});
I hope this working with you, I have created example you will be woking with document.ready it means JQuery see and focus on all elements in your web page, here is fiddle
Simple for test
<div id="slider-pre-loader">no</div>
<div id="video-blog-slider" style="display: none">
hi
</div>
OR your code
<div id="slider-pre-loader">no</div>
<div id="video-blog-slider" style="display: none">
<div class="blog-category-items blog-page" id="blogIndex">
<div class="container">
<?php
$hpos = 0;
foreach ($categories as $category):
$categoryhref = fakeUrl::genSlugFromText($category['name']);
$listVideos = $category['videos'];
if (in_array($category['name'], $categoryDisplay)) :
?>
<div class="blog-groups">
<div class="group-heading">
<h3>
Test title
</h3>
</div>
<?php if ($category['desc'] != '') :?>
<p class="group-desc"><?php echo $category['desc'];?></p>
<?php endif;?>
<?php
$slideClass = '';
if (!$detect->isMobile() && !$detect->isTablet() ) {
$slideClass = 'blog-slider';
}
?>
<div class="<?php echo $slideClass;?> owl-lg-dot mb-none owl-theme owl-loaded" id="videoList">
<?php
$v = 0;
foreach ($listVideos as $video) :
$v++;
$itemClass = '';
if (($detect->isMobile() || $detect->isTablet()) && $v > 5) {
$itemClass = 'item-disable';
}
$videoSlug = fakeUrl::genSlugFromText($video['title']);
?>
<div class="blog-item <?php echo $itemClass;?>">
<div class="blog-image">
<a href="/blog/<?php echo $videoSlug; ?>" title="<?php echo $video['title'];?>">
</a>
</div>
<div class="caption">
<a class="blog-list-video-title" href="/blog/<?php echo $videoSlug; ?>" title="<?php echo $video['title'];?>">
</a>
</div>
<div class="blog-metas">
<small class="blog-views"><?php echo number_format($video['views']); ?> views</small>
</div>
</div>
<?php
endforeach;
?>
</div>
</div>
<?php
endif;
endforeach;
?>
</div>
</div>
</div>
Javascript:
$(document).ready(function() {
$("#slider-pre-loader").fadeOut('slow');
$("#video-blog-slider").fadeIn('slow');
});

Error on Infinite scroll with Ajax, PHP and MySQL

I am trying to implement an infinite scroll in my application but at the moment of reaching the end of my page, this throws the error that places.
This is the ajax code:
<script type="text/javascript">
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
var last_id = $(".post-id:last").attr("id");
loadMoreData(last_id);
}
});
function loadMoreData(last_id){
$.ajax(
{
url: '/loadMoreData.php?last_id=' + last_id,
type: "get",
beforeSend: function()
{
$('.ajax-load').show();
}
})
.done(function(data)
{
$('.ajax-load').hide();
$("#post-data").append(data);
})
.fail(function(jqXHR, ajaxOptions, thrownError)
{
alert('server not responding...');
});
}
</script>
Here, is where I show the data from th DataBase:
<?php while ($post = $result -> fetch(PDO::FETCH_ASSOC)){ ?>
<div class="box-list" id="post-data">
<div class="item">
<div class="row">
<p class="post-id hidde" id="<?php echo $post['id']; ?>">
<div class="col-md-1 hidden-sm hidden-xs">
<div class="img-item"><img src="<?php echo OTRA; ?>/images/<?php echo $post['thumb']; ?>" alt=""></div>
</div>
<div class="col-md-11">
<h3 class="no-margin-top"><?php echo $post['titulo']; ?> <i class="fa fa-link color-white-mute font-1x"></i></h3>
<h5><span class="color-black"><?php echo $post['company']; ?></span> - <span class="color-white-mute"><?php echo $post['locacion']; ?></span></h5>
<p class="text-truncate "><?php echo $post['extracto']; ?></p>
<div>
<span class="color-white-mute"><?php echo fecha($post['fecha']); ?></span>
</div>
</div>
</div>
</div>
</div>
<?php } ?>
and this id the other PHP file to load more data:
<?php session_start();
require 'extras/config.php';
require 'functions.php';
comprobarSession();
$conexion = conexion($bd_config);
$qry = "SELECT * FROM publications WHERE id > '$_GET['last_id']' ORDER BY id DESC LIMIT 8";
$result = $conexion->query($qry);
print_r ($result);
$json = include('views/empleos.php');
echo json_encode($json);
on the Developer Tool of Chrome the error that show me is
jquery.js:8706 GET http://localhost/loadMoreData.php?last_id=9 404 (Not Found)
What is the name of that php file? Sounds like it is not loadMoreData.php? Perhaps it is loadData.php, and the AJAX call should be changed?

After jquery auto refresh a div popup doesnt work

I have a jquery which refreshes the div but after refresh the popup doesn't work from the refreshed data.
<script type="text/javascript">
$(function() {
$.ajaxSetup ({
cache: false
});
//Refresh trigger `#newORDERx`
var auto_refreshes = setInterval(function () {$('#newORDERx').load('inc/restAdmin_orders_rcvz.php');}, 1000);
});
</script>
<div id="newORDERx"></div>
When i use it like below then popup works fine but then it doesn't refresh the div.
<script type="text/javascript">
$(document).ready(function(){
$.ajaxSetup ({
cache: false
mainClass: 'pp-product-detail' // when i use this then popup works but then doesn't refresh the div
});
var auto_refreshes = setInterval(function () {$('#newORDERx').load('inc/restAdmin_orders_rcvz.php');}, 1000);
});
</script>
pp-product-detail class
AJAX popup
if ($('.pp-product-detail').length) {
$('.pp-product-detail').magnificPopup({
type: 'ajax'
});
}
restAdmin_orders_rcvz.php
<div class="col-lg-6">
<div class="the-menu-item">
<div class="image-wrap">
<a class="pp-product-detail" href="product-detail-popup-rest-admin-order-rcv.php?iid=<?php echo $phporder; ?>">
<img src="images/themenu/img-1.jpg" alt="">
</a>
</div>
<div class="the-menu-body">
<b><font color='red'> Order # </font> <?php echo $phporder; ?><br>
<font color='red'> Items Included : </font> <?php echo $lrsa['count']; ?>
<br><font color='red'>Dated : </font> <?php echo date("d/m/Y", strtotime($phpdates)); ?>
</b>
</div>
</div>
</div>
Okay... I'm pretty sure that the problem is in your class, since you re-write the .pp-product-detail element...
So try to change it to this:
if ($(document).find('.pp-product-detail').length) {
$(document).find('.pp-product-detail').magnificPopup({
type: 'ajax'
});
}
I have just added following file in restAdmin_orders_rcvz.php and its working fine.
<script type="text/javascript" src="js/scripts.js"></script>
restAdmin_orders_rcvz.php
<div class="col-lg-6">
<div class="the-menu-item">
<div class="image-wrap">
<a class="pp-product-detail" href="product-detail-popup-rest-admin-order-rcv.php?iid=<?php echo $phporder; ?>">
<img src="images/themenu/img-1.jpg" alt="">
</a>
</div>
<div class="the-menu-body">
<b><font color='red'> Order # </font> <?php echo $phporder; ?><br>
<font color='red'> Items Included : </font> <?php echo $lrsa['count']; ?>
<br><font color='red'>Dated : </font> <?php echo date("d/m/Y", strtotime($phpdates)); ?>
</b>
</div>
</div>
</div>

How to show check box text if it is not next to check box using jQuery

I am trying to achieve checked value text should visible like shown in the image:
Without refresh or any click can anyone help me out?
This is my php dynamic from :
<div class="products-row">
<?php $tq=$conn->query("select * from os_tiffen where tiffen_status=1 order by id_tiffen ASC");
while ($tiffen = $tq->fetch_assoc()) {
?>
<div class="col-md-3">
<div class="foodmenuform row text-center">
<input multiple="multiple" type="checkbox" id="<?php echo $tiffen['tiffen_image']; ?>" name="tifeen" hidden>
<label for="<?php echo $tiffen['tiffen_image'];?>"><img src="img/tiffen/<?php echo $tiffen['tiffen_image']; ?>" class="img img-responsive" /></label>
<h3 class="FoodName"><?php echo $tiffen['tiffen_name'];?></h3>
</div>
</div>
<?php } ?>
</div>
This is my script to show the text:
<script type="text/javascript" language="JavaScript">
$( document ).ready(function() {
var FoodMenu = $('input[type=checkbox]:checked').map(function(){
return $(this).next('.FoodName').text();
}).get().join("<br>");
$("#selectedfood").html(FoodMenu);
});
</script>
Out put id: <a id="selectedfood"></a></li>
You could try to get all checked options’ text on checkbox change event and append selected values to “selectedfood”. The following sample code is for your reference.
<script>
$(function () {
$(".foodmenuform [type='checkbox']").change(function () {
var FoodMenu = "";
var ischecked = $(".foodmenuform [type='checkbox']:checked").each(function () {
FoodMenu += $(this).siblings(".FoodName").text() + "<br/>";
})
$("#selectedfood").html(FoodMenu);
})
})
</script>
Its easier thank i thought:
var checkedFood = $('input[type=checkbox]:checked').map(function(){
//console.log($('input[type=checkbox]:checked').serialize());
return $(this).val();
}).get().join("<br>");
$("#selectedfood").html(checkedFood);
Form:
<div class="products-row">
<?php $tq=$conn->query("select * from os_tiffen where tiffen_status=1 order by id_tiffen ASC");
while ($tiffen = $tq->fetch_assoc()) {
?>
<div class="col-md-3">
<div class="foodmenuform row text-center">
<input type="checkbox" id="<?php echo $tiffen['id_tiffen'];?>" class="Foodmenu" value="<?php echo $tiffen['tiffen_name'];?>" name="tifeen[]" hidden>
<label for="<?php echo $tiffen['id_tiffen'];?>"><img src="img/tiffen/<?php echo $tiffen['tiffen_image']; ?>" class="img img-responsive" /></label>
<h3><?php echo $tiffen['tiffen_name'];?></h3>
</div>
</div>
<?php } ?>
</div>

Trying to display data shown depending on what users click

Have a look here:
http://test.neworgan.org/100/
Scroll down to the community section.
What I'm trying to achieve is to get the data for new organizers, (e.g.: number of friends / amount donated) to show once users click on their thumbnails. right now each user has his or her own unique data stored externally.
Once the users click the thumbnail, 'inline1' appears with the content.
As of now, I'm only able to get the data from the last user to show regardless of whichever user's thumbnails I'm clicking on. I just need a bit of help as to how to change the content depending on which thumbnail users click. So I was wondering if I could have some help here?
Here's that part of the code that matters:
<div class="top-fundraisers-wrapper">
<div class="subsection top-fundraisers">
<?php if ($top_fundraisers && is_array($top_fundraisers)): ?>
<?php foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline1">
<div class="top-fundraiser">
<div id="newo<?php print htmlentities($index + 1); ?>" class="top-fundraiser-image">
<img src="<?php
if($fundraiser['member_pic_medium']) {
print htmlentities($fundraiser['member_pic_medium']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
</div>
</a>
<?php endforeach;?>
<?php endif; ?>
</div>
</div>
</div>
<div id="inline1">
<div class="top-fundraiser-image2">
<img src="<?php
if($fundraiser['member_pic_large']) { print htmlentities($fundraiser['member_pic_large']);
} else {
print $template_dir . '/images/portrait_placeholder.png';
}
?>"/>
</div>
<span class="member-name"><?php print htmlentities($fundraiser['member_name']); ?></span>
<span class="friend-count"><?php print number_format($fundraiser['num_donors']) . (($fundraiser['num_donors'] == 1) ? ' Friend' : ' Friends'); ?></span>
<span class="fundraisers-text"> Donated: </span><span class="fundraisers-gold"> $<?php print number_format($fundraiser['total_raised']); ?></span>
</div>
Best way is to use Ajax. Something like this
$("#button").click( function() {
$.ajax({
url: 'file.php',
method: 'post',
data: { id: $(this).val() },
error: function() {
alert('error while requesting...');
}, success: function(data) {
alert( data ); /** received data - best to use son **/
}
});
});
Next parse json var json = $.parseJSON(data);
or ... use dataJson option.
Next Your data should be inserted using class or id to specific location.
Create another loop for content
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<a title="" class="fancybox" href="#inline<?php echo $i; ?>">
// ... content
<?php $i++;
endforeach;
endif; ?>
And another loop
<?php if ($top_fundraisers && is_array($top_fundraisers)):
$i = 1;
foreach ($top_fundraisers as $index => $fundraiser): ?>
<div id="inline<?php echo $i; ?>">
// inline content here
</div>
<?php $i++;
endforeach;
endif; ?>
Hope your JavaScript function to open fancybox works fine via calling class. So by following code you do not need to play with Javascript code.
Building anchors tags:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<a title="" class="fancybox" href="#inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</a>
<?php
} //end of foreach
} // end of if condition
?>
Building Popup HTML DOMs:
<?php
if (!empty($top_fundraisers) && is_array($top_fundraisers)) {
foreach ($top_fundraisers as $index => $fundraiser) {
<div id="inline<?php echo $fundraiser['id']; ?>">HTML Content Goes Here</div>
<?php
} //end of foreach
} // end of if condition
?>
You cannot perform this because PHP runs server-side and JavaScript runs in the browser.
To perform this you can use AJAX to get the div as required by user.
...or store the data client-side and change the content of #inline1 based on which item was clicked

Categories