Remove DIV only if empty - php

I have a PHP notification system, and the amount of notifications is put into a DIV using jQuery. The only problem is that when there are 0 notifications, the empty DIV still shows up. This is the jQuery I am currently using:
$(document).ready(function() {
$.get('/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
});
setInterval(function() {
$.get('http://localhost/codes/php/nf.php', function(a) {
$('#nfbadge').html(a);
$('#nfbadge:empty').remove();
})
}, 8000);
The only problem is that if at document load there is 0 notifications and a notification is added, the badge will not show up, so basically if the element is removed it won't come back unless the page is reloaded, but I made the notification system so that the page wouldn't have to be reloaded. How can I fix this?

.remove() takes the element out of the DOM as well as the content. This is why it doesn't come back unless you reload. Use .fadeOut() or .hide() instead

You should probably do something more like this:
var elm = $('#nfbadge'),
T = setInterval(getCodes, 8000);
function getCodes() {
$.get('/codes/php/nf.php', function(a) {
elm.html(a);
if (elm.is(':empty') && elm.is(':visible')) {
elm.hide();
}else{
elm.show();
}
});
}
Will need some more work on your part, but should get you on the right track!

If you have control over the PHP, you shouldn't be using jQuery to be removing DIVs, it's a waste of resources and load time, even if it's just a few lines of code.
In your PHP template you should include the #nfbadge div in a conditional statement, something like:
if($notifications) {
echo '<div id="nfbadge">';
//notification stuff
echo '</div>';
}
Then with your jQuery code you could do something like the following:
var $nfbadge = $('#nfbadge');
if($nfbadge) {$nfbadge.html(a)}

Why don't you just make the div hidden?
http://www.randomsnippets.com/2008/02/12/how-to-hide-and-show-your-div/

Related

Bootstrap alert won't close after initial appearance

This is a very difficult problem to explain and demo, basically I am using a mixture of PHP, Smarty, Ajax and Bootstrap.
I have a smarty template with an Ajax form in it (this works), a PHP backend which adds the form details into a database (this also works), on success or failure an alert is shown, this alert is from the Bootstrap CSS, it is written to the page as follows.
$('form').append('<div class="alert alert-success alert-dismissible" role="alert">' + data.message + '×</div>');
The alert does display in the page, and the alert does close! However, for example if I or the user should want to use the form again for example, to say add another record to the database, the alert does show, but this time it never closes! So if I add another 10 records and click the submit button after each one as normal I have 10 alert boxes under the form that never close.
<script type="text/javascript">
window.setTimeout(function() {
$(".alert").fadeTo(1000, 0).slideUp(1000, function() {
$(this).hide();
});
}, 5000);
</script>
Does anyone have an idea as to what I could do instead that would work perhaps?
The below code closes the alert, but there is some inconsistency as to when the alert closes.
$(document).ready(function() {
$('form').submit(function(event) {
// snip
var alertTimer1 = window.setInterval(function() {
if (typeof alertTimer2 === 'undefined') {
var alertTimer2 = window.setTimeout(function() {
$('#alert').find('.alert').fadeTo(1000, 0).slideUp(1000, function() {
$(this).remove();
window.clearInterval(alertTimer1);
window.clearTimeout(alertTimer2);
});
}, 5000);
}
}, 100);
}
}
setTimeout function only execute once where setInterval checks on a regular time interval. For example: https://codepen.io/anon/pen/VGPYXB
The better solution could be when you adding alert message set setTimeout function after adding message or use delay function like this https://codepen.io/anon/pen/XPpJGe.
Initializing alert with $('.alert').alert()
Close it with $('.alert').alert('close') or $('.alert').alert('dispose')
Add the code lines within setTimeout() to delay event like so:
setTimeout(() => {
$('.alert').alert('close')
}, 10000)
Bootstrap 3.3 Documentation - Alerts
Bootstrap 4.0 Documentation - Alerts
use bootstrap's alert class. It will help you close the alert box elegantly.

Ajax div refresh (without fading in and out)

So i have looked around and most of the code for this looks needlessly beefy. I am looking for lightweight ajax code that refreshes a div with an action like:
load('boo.php')
And I need it to load first on the page opening (ie no delay) then every x seconds refresh (without fade) so you cannot notice a change unless my Database rows have updated but I can do the db bit.
I think i would need something like:
onreadystatechange
to load when the page loads? Eh im not too sure on this :( any help would be much appreciated!
Thanks!
I totally recommend using some library for cross-browser support and tested code, e.g. jQuery.
With jQuery, it's as simple as
$.get('boo.php', function(data){$('#divId').html(data);});
You can wrap this in a function and call it on document ready, then use setInterval as suggested by #M1K1O
Update
To run the code when the DOM is loaded, the jQuery API documentation for ready states that
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not
recommended)
$(handler)
Here is a complete example:
function refreshDiv()
{
$.get('boo.php', function(data){$('#divId').html(data);});
}
$(function()
{
refreshDiv();
setInterval(refreshDiv, x * 1000); // x is the number of seconds
});
var counter = 0;
var timer = null;
function progressBar(){
if (timer) {
clearTimeout(timer);
timer = null;
return;
}
timer = window.setInterval(function(){
load('boo.php');
}, 10);
}
window.onload = function() {
progressBar();
};
Try this
Do you use some libries like Jquery ?
Here is some code on jquery for.
function update()
{
$.get(<URI>,{check:1},function(data){
$('#div').html(data);
});
setTimeout('update()',1500);
}
$(function(){
update();
});

How to check for contents of a loaded div tag using jquery load?

I'm working with jqueries address change event and am hitting a roadblock when a user copies and pastes a URL in the browser. I need to fist load a portion of the page that contains a form. I could do this after every pagination call but it seems really ineffecient.
Here is my current code block:
$.address.change(function(e) {
var urlAux = e.value.split('=');
var page = urlAux[0];
var start = urlAux[1];
if (page == "/visits") {
$.address.title("Profile Views");
if (start) {
$('#start').val(start);
// ***** If a user has copied and pasted this URL with a start value then I first need to load visits.php in the main div tag. Is it possible to see if this is loaded or not?
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
}
else {
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () { });
}
}
My attempted work around was this:
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
There must be a better way...this is realoading the same portion of the page (visits.php) with every pagination event. Is there a better way to load URLs and not have them trigger an address change?
Using paul's work around from his comments, but instead of Regex'ing html content in the visits.php form this solution will look for data() attached to #mainID.
Paul's work around notes:
After a bit more hacking I came up with this solution that seems to do
the trick. I'm not sure how good it is but it seems to do the trick. I
now get the main div id and do a regex match on a unique string in the
form. If I don't see it I load the form and then load the results. Not
sure if this is good practice or not but it seems to solve my issue.
Methodology to use .data() instead of a regex search of visits.php's html:
/*check if we're missing visits.php by looking for data() flag*/
if( !($("#main").data()["hasVisitsPhp"]) ){
var args = localStorage.getItem("visits");
$('#main').load("visits.php?" + args, function () {
$('#start').val(start);
$.post("visits_results.php", $("#profile_form_id").serialize(),
function(data) {
/* we've loaded visits.php, set the data flag on #main*/
$('#main').data("hasVisitsPhp","loaded");
$('#search_results').html(data);
location.href = "#visits=" + start;
});
});
}
try window.location.hash instead. Changing the whole href can/will trigger a whole-page reload, while changing just the hash by itself should at most cause the page to scroll.

JQUERY: How do I know if this element is currently open/closed (slidetoggle)

Im using the following to open/close a div
$(".alerts").click(function(){
$(this).toggleClass("active").next().slideToggle(50);
But I want a certain function to trigger only if the box was closed and is being opened, how can I determine this? I prefer not to use cookies or anything like that
thanks!
You can use the visible selector with the is method like this -
$(document).ready(function()
{
$(".alerts").click(function()
{
if($(this).toggleClass("active").next().is(":visible"))
alert("It's visible");
$(this).toggleClass("active").next().slideToggle(50);
});
});
An example on jsfiddle.
The -
if($(this).toggleClass("active").next().is(":visible"))
alert("It's visible");
portion is checking to see if the next element of this is visible or not. If it is, then it returns true. As a result, the alert method gets executed.
Here is the documentation for the visible selector and here is the documentation for the is() method.
You can add a class to the div and check for it with hasClass():
$('.alerts').live('click', function() {
if($(this).hasClass('active')) //close
$(this).removeClass('active').next().slideUp(50);
else //open
$(this).addClass('active').next().slideDown(50);
});
When checking for DOM elements/attributes that have been changed by Javascript, use live() rather than e.g. click().
If your .alerts element has a different CSS style when it has the .active class, you should run the addClass() and removeClass() functions after the slide events have completed, like so:
//same thing, but wait for animation to complete
$('.alerts').live('click', function() {
var thisbtn = $(this);
if(thisbtn.hasClass('active')) { //close
thisbtn.next().slideUp(50, function() {
thisbtn.removeClass('active');
});
} else { //open
thisbtn.next().slideDown(50, function() {
thisbtn.addClass('active');
});
}
});

JQuery and PHP Infinite Scrolling Help

I'm having a problem with my infinite scrolling. As I scroll down, it loads the next items fine but it keeps sending those items. I've been using this jquery to give it a unique id because I have ordered the items with mysql with an algorithm:
$("#image-list li").each(function(index) {
$(this).attr('id', index);
});
and inorder to label the newly given items from an external php file, I have to use this code in the file as well.
To send the information about the items given, I've been using this jquery:
function last_db_item_function()
{
var ID=$(".db-item:last").attr("id");
$('div#last-db-item-loader').html('<img src="loading.gif" height="30px" />');
$.post("index.php?action=get&last_db_item="+ID,
function(data){
if (data != "") {
$(".db-item:last").after(data);
}
$('div#last-db-item-loader').empty();
});
};
$(window).scroll(function(){
if ($(window).scrollTop() == $(document).height() - $(window).height()){
last_db_item_function();
}
});
but the problem is that it does not seem to work. Which I mean it doesn't not gather that last item id from the newly parsed php file. To parse the php I've been doing this:
$last_db_item = $_GET['last_db_item'];
$action = $_GET['action'];
if($action != "get")
{
.... Code Here....
}else{
include ('secondimages.php');
}
So my question is, why does this seem to go on forever?
It looks like you're never assigning a new ID to the new elements when you append them to the list. The first snippet you have either needs to be called after every new element is added, or similar code needs to be applied to that one element when you add it (unless it's coming back in the php, at which point we'd need to know more about what you're returning)

Categories