JavaScript Isotope classes not loaded after AJAX - php

I am pulling the 50 most recent records from a mySQL database. Each goes into a DIV which has Isotope and works perfectly - DIVs animate, reset, etc.
Using AJAX to call for the next 50 records using OFFSET, however, the new records load into new DIVs but Isotope's classes are not applied to them (as seen via Web Inspector.)
THE SET UP:
index.php = calls the database when loaded in the browser, Isotope works fine. A link on index.php (a#update_newImages) triggers a listener to load "load-ajax.php".
load-ajax.php = an external page which only has the SQL SELECT and PDO loop. These records load but w/o Isotope applied, thus the problem.
code from index.php
...database connection info and query code go here
$filter = ""; // appears in the echo'd DIV below, for filtering the ISOTOPE divs. Turned off til this injection problem is solved
//ISOTOPE SETTINGS, in <HEAD>
var $container = $('#theContent');
$container.isotope({
layoutMode : 'fitRows', //leave blank for default masonry
filter: '*',
animationOptions: {
duration: 750,
easing: 'linear',
queue: false,
}
});
in BODY:
<div id="theContent">
<?php
for($i=0; $links = $query_links->fetch(); $i++){
echo "<div class=\"".$filter." box\">" . $links['ATtitle']."<br>" . "#" . $links['LID']."-
". $links['descr']."</div>";
}
?>
</div><!-- theContent -->
<script> // RIGHT BEFORE BODY TAG CLOSES
var offset_newImages = 0; // initial offset value
var newImages = document.getElementById('update_newImages'); // a link on the page
newImages.addEventListener('click', function() {
event.preventDefault();
offset_newImages += 50; // increments batches of records
$.get('load-ajax.php?loadDataType=newImages&offset='+offset_newImages, function(data) {
$("#theContent").hide().html(data).fadeIn(600);
//**EDIT**
alert('Load was performed.'); // callback on success, works - is this where the Isotope "appended" code would go?
}, false);
});
</script>
code from load-ajax.php
...database connection info goes here
$offset = $_GET["offset"]; // from URL
$filter = ""; // for filtering the ISOTOPE divs, turned off til the injection problem is solved
for($i=0; $links = $query_links->fetch(); $i++){
$showList = "<div class=\"".$filter." box\">" . $links['ATtitle']."<br>" . "#" . $links['LID']."-
". $links['descr']."</div>";
echo $showList; // this is where ISOTOPE is not applied after each AJAX injection
}
I am thinking there is a call back solution but am unsure what to do next.
NOTE: I have experimented with the Isotope + infinite scroll by Paul Irish, but cannot use it here until I can convert infinite scroll's paging mechanism to JSON from mySQL. Next project.
EDIT: I have revised index.php to read as follows. The problem persists, but I think it's almost there. The ajax is working, but when Isotope kicks in it does not add its classes on the new DIVs.
<head>
<script type="text/javascript">
$(document).ready(function(){
//ISOTOPE SETTINGS
var $container = $('#container');
$container.isotope({
layoutMode : 'fitRows', //leave blank for default masonry
filter: '*',
animationOptions: {
duration: 750,
easing: 'linear',
queue: false,
}
});
});
</script>
goes right before </body>:
<script>
var offset_newImages = 0; // initial offset value
var newImages = document.getElementById('update_newImages'); // a link on the page
newImages.addEventListener('click', function() {
offset_newImages += 50;
$.ajax({
type: 'GET',
url: "load-ajax.php?offset="+offset_newImages,
success:function(data){
// alert(data); // works
$("#container").hide().html(data).fadeIn(600) // fades in the new recordset
$container.isotope('insert', data);
}
});
});
</script>
So to wrap up, the new data loads into the DIVs - I can see it until I resize the browser window in any way, which is where Isotope kicks in and hides the new DIVs with its CSS.

Isotope has a number of methods for recalculating the layout after dynamically inserting new content.

Related

AJAX Chat Box Scrolling Up Issue

Hi I am writing a chat website and I have a problem with the div containing the messages. In the CSS the div containing the messages has overflow: auto; to allow scroll bars. Now the problem is when ajax is fetching the messages through a PHP script that fetches the messages from the database, you cannot scroll up. The AJAX refreshMessages() function is set to update every second using window.setInterval(refreshMessages(), 1000);. This is what I want but when I scroll up to see previous messages, the scroll bar hits straight back down to the end of the chat due to the AJAX fetch function.
Any ideas of what the issue is?
AJAX Code:
//Fetch All Messages
var refreshMessages = function() {
$.ajax({
url: 'includes/messages.inc.php',
type: 'GET',
dataType: 'html'
})
.done(function( data ) {
$('#messages').html( data );
$('#messages').stop().animate({
scrollTop: $("#messages")[0].scrollHeight
}, 800);
})
.fail(function() {
$('#messages').prepend('Error retrieving new messages..');
});
}
EDIT:
I'm using this code but it isn't quite working, it pauses the function but then the function doesn't restart when the scroll bar goes back to the bottom. Help?
//Check If Last Message Is In Focus
var restarted = 0;
var checkFocus = function() {
var container = $('.messages');
var height = container.height();
var scrollHeight = container[0].scrollHeight;
var st = container.scrollTop();
var sum = scrollHeight - height - 32;
if(st >= sum) {
console.log('focused'); //Testing Purposes
if(restarted = 0) {
window.setTimeout(refreshMessages(), 2000);
restarted = 1;
}
} else {
window.clearInterval(refreshMessages());
restarted = 0;
}
}
You need to replace the checkFocus() function to return true or false and then get AJAX to check if it need's to send the scroll bar down after adding in the new message or not. Replace the checkFocus() function with this:
//Check If Last Message Is In Focus
var checkFocus = function() {
var container = $('.messages');
var height = container.height();
var scrollHeight = container[0].scrollHeight;
var st = container.scrollTop();
var sum = scrollHeight - height - 32;
if(st >= sum) {
return true;
} else {
return false;
}
}
Change AJAX .done to this:
.done(function( data ) {
if(checkFocus()) {
$('#messages').html( data );
scrollDownChat();
} else {
$('#messages').html( data );
}
})
To answer your question of what's happening: the interval runs every second, and when you have scrolled up during that waiting period, it'll run again and move you down 800 pixels. You can remove this from your function to do this.
Since you're using overflow: auto, your chat box will grow and create a scrollbar when necessary. Have you tried removing the scroll functionality? Does it not move to the latest text at the bottom?
If not, then you can check if user has scrolled or not, when user has scrolled, you should not scroll using jQuery. To do this, you can add a variable outside this function which gets updated if user scrolls at all.
Detecting between user scrolling and your javascript scrolling is not easy, so you can use which message(s) is(are) being viewed. If the message in focus is the last message, you should keep scrolling to the bottom, but when the last message goes out of view, you can assume user has scrolled.
See this question for more info on detecting scroll: Detect whether scroll event was created by user

Jquery selector not working after append

I have a php script that I call that returns html in a way that it can be directly inserted into a container or the body and just work (E.X. '<image id="trolleyLogoEdge" class="pictureFrame party" src="tipsyTrixy.png" >'). After appending this text to a div the selector $('#pictureFrame > img:first') won't work. I'm not using event handlers or anything so I don't know why I'm having an issue. My code worked fine when I just had the image tags in the div without any manipulation so I'm assuming it must be a selector issue. I have tested my php output and it is exactly matching the html that was in the div before I decided to dynamically populate the div.
var classType = '';
var classTypePrev = '';
var width = $(window).width();
var height = $(window).height();
var size = (height + width)/2;
var time = 0;
$( document ).ready(function()
{
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
startSlideshow($('#pictureFrame > img:first'));
});
});
window.onresize = function()
{
width = $(window).width();
};
function startSlideshow(myobj)
{
classType = $(myobj).attr('class').split(' ')[1];
if(classTypePrev != classType)
{
$('.picDescription').animate({'opacity': "0"},{duration: 2000,complete: function() {}});
$('.picDescription.' + classType).animate({'opacity': "1"},{duration: 3000,complete: function() {}});
}
classTypePrev = classType;
myobj.animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) - 150), opacity: '1'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function() {}}).delay(2000).animate({left: "-=" + ((width/2)+ ($(myobj).width()/2) + 150), opacity: '0'},{
duration: 5000,
'easing': 'easeInOutCubic',
complete: function()
{
$(myobj).css("left", "100%");
}
});
setTimeout(function()
{
var next = $(myobj).next();
if (!next.length)
{
next = myobj.siblings().first();
}
startSlideshow(next)},9000);
}
Your code that appends the data to the frame has a typo in the ID selector.
$.post( "pictureDirectory.php", function( data )
{
$('#picureFrame').append(data);
^^here
startSlideshow($('#pictureFrame > img:first'));
});
It should probably be
$('#pictureFrame').append(data);
.find() gets the descendants of each element in the current set of matched elements.
> selects all direct child elements specified by "child" of elements specified by "parent".
Try:
startSlideshow($("#pictureFrame").find("img:first"));
If img is not direct child of #pictureFrame, .find() should work.
You should know the difference between
Delegated Event
Direct Event
check this for the difference between direct and delegated events.
If we were to click our newly added item, nothing would happen. This is because of the directly bound event handler that we attached previously. Direct events are only attached to elements at the time the .on() method is called. In this case, since our new anchor did not exist when .on() was called, it does not get the event handler.
check this link to official JQuery Document for further clarification.

Unable to navigate Dynamically created pages in DOM

After so many trials, I have finally managed to create pages dynamically using PHP, JSON and AJAX and load them into DOM. But the problem now is I'm unable to call/navigate those pages dynamically, but manually i.e gallery.html#page1 ...etc.
I seek guidance rather than burdening you, as I'm here to learn.
**PHP - photos.php **
$photos = array();
$i=0;
while ($row = mysqli_fetch_array($query)){
$img = $row["fn"];
$photos[] = $img;
$i++;
}
$count = count($photos);
echo json_encode(array('status' => 'success', 'count' => $count, 'items' => $photos));
JSON array
{
"status":"success",
"count":3,
"items":
[
"img1.jpg",
"img2.jpg",
"img3.jpg"
]
}
I use the below method to fetch and store ID of the desired gallery,
<input type="hidden" value="<?php echo $id; ?>" id="displayid" />
and then I call it back to use it in AJAX.
var ID = $('#displayid').val();
AJAX and JQM
$.ajax({
Type: "GET",
url: 'photos.php',
data: { display: ID }, // = $('#displayid').val();
dataType: "json",
contentType: "application/json",
success: function(data) {
var count = data.count;
var number = 0;
$.each(data.items, function(i,item) {
var newPage = $("<div data-role=page data-url=page" + number + "><div data-role=header><h1>Photo " + number + "</h1></div><div data-role=content><img src=" + item + " /></div></div");
newPage.appendTo( $.mobile.pageContainer );
number++;
if (number == count) { $.mobile.changePage( newPage ); }; // it goes to last page
I got this code from here thanks Gajotres to dynamically navigate between pages. It's within the same code.
$(document).on('pagebeforeshow', '[data-role="page"]', function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.activePage.find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'b'}).addClass('ui-btn-right').html('Next').button());
}
}); // next button
}); // each loop
} // success
}); //ajax
I found your problem.
This part of code can't be used here like this:
$(document).on('pagebeforeshow', '[data-role="page"]', function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$.mobile.activePage.find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'b'}).addClass('ui-btn-right').html('Next').button());
}
});
This is the problem. First remove pagebeforeshow event binding, it can't be used here like that. Rest of the code is not going to do anything because currently there are any next page (next page is going to be generated during then next loop iteration), so remove this whole block.
Now, after the each block ends and all pages are generated (that is the main thing, all pages should exist at this point), add this code:
$('[data-role="page"]').each(function(){
var nextpage = $(this).next('div[data-role="page"]');
if (nextpage.length > 0) {
$(this).find('[data-role="header"]').append($('<a>').attr({'href':'#'+nextpage.attr('id'),'data-theme':'a'}).addClass('ui-btn-right').html('Next').button());
}
});
This is what will happen. Each loop will loop through every available page (we have them all by now) and in case it is not the last one it will add next button.
Here's a live example: http://jsfiddle.net/Gajotres/Xjkvq/
Ok in this example pages are already there, but point is the same. They need to exist (no matter if you add them dynamically or if they are preexisting) before you can add next buttons.
I hope this helps.

Grabbing div content and sending to php email

New here and glad to be, I've gotten a lot of answers from this forum. I am however stuck at the moment.
I have some javascript that is creating a window color and handle picker (click on the color swatch it changes the image, click on a handle and it does the same). Below the image is a description of the window selected. This text is being generated by the javascript by pulling the image titles.
Now the fun part. Below this picker I need to add a form that will be emailed using php. Within that email I need to pull the window description that is being generated by the javascript.
I have tried so many things today I have lost count. The last bit of code I tried was
<script>
$(document).ready(function() {
$("windowDesc").each(function() {
var html = jQuery(this).html();
});
});
</script>
And in the php mail file I added:
$windowtitle = $_GET['html'];
as well as trying
$windowtitle = $_POST['html'];
and I have also tried the following:
<script>
var content = $('#windowDesc').html();
$.ajax({
url: 'send_mail.php',
type: 'POST',
data: {
content: content
}
});
</script>
And in the php mail file I added:
$windowtitle = $_GET['content'];
as well as trying
$windowtitle = $_POST['content'];
Not to mention a plethora of other things.
Basically what I am trying to do is grab the content of the div that holds the generated text and email it. If any of the above are correct then I must be placing them in the wrong position or something. With the first one I have tried it inside the form, outside the form, before the div, after the div. Just haven't tried it on top of my head yet. It's been a long day, thanks in advance :o)
Sorry for the delay, been a busy two days. OK, so here is the code that handles the window color and handle picker:
var Color = "color";
var Handle = "handledescription";
var ColorDesc = "color";
var HandleDesc = "handle description"
function Window(Color,Handle,ColorDesc,HandleDesc) {
$('#windowPic').animate({opacity: 0}, 250, function () {
thePicSrc = "http://www.site.com/images/windows/" + Color + Handle + ".jpg";
$('#windowPic').attr('src', thePicSrc);
$('#windowDesc').html("<p>" + ColorDesc + " frame with " + HandleDesc + " hardware</p>");
$('#windowPic').animate({opacity: 1}, 250)
})
}
$(document).ready(function() {
$('#wColors li').click( function() {
Color = $(this).attr('id');
ColorDesc = $(this).attr('title');
Window(Color,Handle,ColorDesc,HandleDesc);
});
$('#wHandles li').click( function() {
Handle = $(this).attr('id');
HandleDesc = $(this).attr('title');
Window(Color,Handle,ColorDesc,HandleDesc);
});
});
You need a hidden input in your form:
<form id="send_email" action="send_email.php">
<input id="content" type="hidden" name="content"/>
... other inputs here
</form>
Then you can use Javascript to fill it in before submission:
$("#send_email").submit(function() {
$("#content").val($("#windowDesc").html());
}
<script>
var content = $('#windowDesc').html();
$.ajax({
url: 'send_mail.php',
type: 'POST',
data: content
});
</script>
It worked here.

How to append additional data in a specified div using php / ajax

I want to know if there is a way to display an external php file after clicking on a link, and then display another external file right below(not INSTEAD of) it after a different link was clicked. Here is my code.
index.html
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery- 1.2.6.pack.js"></script>
<script type="text/javascript" src="core.js"></script>
</head>
<body>
<div id="menu">
<ul>
<li id="home">DOWNLOADS</li>
<li id="tutorials">ERRORS</li>
</ul>
</div>
<div id="content">
</div>
</body>
</html>
core.js
//On load page, init the timer which check if the there are anchor changes each 300 ms
$().ready(function(){
setInterval("checkAnchor()", 100);
});
var currentAnchor = null;
//Function which chek if there are anchor changes, if there are, sends the ajax petition
function checkAnchor(){
//Check if it has changes
if(currentAnchor != document.location.hash){
currentAnchor = document.location.hash;
//if there is not anchor, the loads the default section
if(!currentAnchor)
query = "page=1";
else
{
//Creates the string callback. This converts the url URL/#main&id=2 in URL/?section=main&id=2
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
//Create the params string
var params = splits.join('&');
var query = "page=" + page + params;
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").html(data);
$("#loading").hide();
});
}
}
downloads.php
<b>DOWNLOADS</b>
errors.php
<b>ERRORS</b>
callbacks.php
<?php
//used to simulate more waiting for load the content, remove on yor projects!
sleep(1);
//Captures the petition and load the suitable section
switch($_GET['page']){
case "errors": include 'errors.php'; break;
case "downloads": include 'downloads.php'; break;
default: include 'downloads.php'; break;
}
?>
This works perfectly except it uses a switch and I want to be able to see both errors.php and downloads.php at the same time, not only one or the other.
EDIT
Pseudo code to make it clearer:
If download is clicked show download.php only. If error is clicked show error.php only(right after downloads.php) and don't remove downloads.php or any other external file that may or may not be included on the main page already.
Any suggestions?
p.s. I've looked through many, many threads about this and that's why I can't post all the code I've tried (sorry I can't include links either, last time my question was downvoted for doing that...>:/) so I can promise I've done my homework.
p.s.s. If you think this deserves a down vote please be kind enough to explain why. I'm open to criticism but just thumbs down is not helpful at all.
EDIT:
Updated core.js to
$(document).ready(function(){
$('#menu li a').click(function() {
var currentAnchor = $(this).attr('href');
if(!currentAnchor)
var query = "page=1";
else
{
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
//Create the params string
var params = splits.join('&');
var query = "page=" + page + params;
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").html(data);
$("#loading").hide();
});
return false;
});
});
EDIT:
[The confusing parts removed here]
--
EDIT:
core.js (revised)
//On load page, init the timer which check if the there are anchor changes each 300 ms
$(document).ready(function(){
$('#menu li a').click(function() {
var currentAnchor = $(this).attr('href');
if(!currentAnchor)
var query = "page=1";
else
{
var splits = currentAnchor.substring(1).split('&');
//Get the section
var page = splits[0];
delete splits[0];
//Create the params string
var params = splits.join('&');
var query = "page=" + page + params;
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").html(data);
$("#loading").hide();
});
return false;
});
}​​​);​​​
--
EDIT:
This one will "append" data [coming from either downloads or errors] to the existing content.
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
Hope this helps.
If you want to show both pages at once, in your callbacks.php page you should be able to do something like this (all I did was remove the switch statement):
include 'errors.php';
include 'downloads.php';
Any reason why you can't do this?

Categories