Bootstrap alert won't close after initial appearance - php

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.

Related

running setTimeout multiple times for ajax call

I have a webpage where a user can post a question, the question is posted and on success response appends text to a div 'your question was posted.' Then the div fades away after 1 second.
If the user posts a second question (without refreshing the page), the question is successfully inserted to the database, but the text is not appending to the div.
Do I need to clear the timeout each time the users posts?
$(document).ready(function(){
$('#postquestion').on('submit',function(e) {
$.ajax({
url:'/question.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
if($.trim(data) == "success") {
$('<div align=\"center\" style=\"padding-top:10px\"><p style=\"font-weight:bold;font-size:14px\">Your question has been posted.</p></div>').appendTo('#product_question');
setTimeout(function() {
$('#product_question').fadeOut('fast');
}, 1000);
}
},
error:function(data){
$("#error").show().fadeOut(5000);
}
});
e.preventDefault();
return false;
});
});
looks like you're calling fadeOut on the div you are appending the the message to, so when it comes back round that div is still hidden when it appends the text
also removing the div from the dom after the fadeOut will make sure that there is only ever one of those divs in the dom at one time
$('<div id=\"test\" align=\"center\" style=\"padding-top:10px\"><p style=\"font-weight:bold;font-size:14px\">Your question has been posted.</p></div>').appendTo('#product_question');
setTimeout(function() {
$('#test').fadeOut('fast').remove();
}, 1000);
Looks like the problem is that the second time it cant apply because your '#product_question' is hidden. Or maybe you have multiple '#product_question' by the time user posts the second question? Maybe you should try using a class 'product_question' instead of id? '.product_question' vs '#product_question' is your styles.
Mate, I guess you're using way too much code in there. Have a hidden div as:
<div id="test" class="myclass" align="center" style="padding-top:10px; display:none;"><p style="font-weight:bold;font-size:14px;">Your question has been posted.</p></div>
and then show it on your call back:
if($.trim(data) == "success") {
$('.myclass').css('display','block');
setTimeout(function() {
$('.myclass').fadeOut('fast');
}, 1000);
}

Reload div using jquery load function working only once and how to pass a variable

I have very limited knowledge with scripts so I hope you guys can help me with a simple solution to a small problem that I have...
I'm using the following jquery function to refresh a div with new content when a link is clicked
<script>
$(function() {
$("#myButton").click(function() {
$("#loaddiv").fadeOut('slow').load("reload.php").fadeIn("slow");
});
});
</script>
My problem is, I need to send 2 variables to the reload.php page to use in a mysql query (I have no idea how to accomplish that), also I need to make multiple links work with this function, at the moment I have multiples links with the same id and only the first link works so I guess I must associate different ids to the function in order for this to work, how can I do that?
here's the page where i'm using this: http://www.emulegion.info/teste/games/game.php
You may want to use document ready instead of function on your first line as this will make sure the code is not executed until the full page (and all elements) have loaded.
You can then use the callback functions of the fade and load to perform actions in a timely manner.
additional variables you can add after the .php, these can then be read in your reload.php file as $var1 = $_GET['var1'];
Do make sure to sanitize these though for security.
<script type="text/javascript">
// execute when document is ready
$(document).ready(function() {
// add click handler to your button
$("#myButton").click(function() {
// fade div out
$("#loaddiv").fadeOut('slow',function(){
// load new content
$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
}); // end load content
}); // end fade div out
}); // end add click to button
}); // end document ready
</script>
For different variables you could add a HTML5 style variable to your button.
<input type="button" id="myButton" data-var1="foo" data-var2="bar" />
You can retrieve this when the button is clicked:
// add click handler to your button
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');
...
load("reload.php?var1="+var1+"&var2="+var2
if you have multiple buttons/links I would use class instead of id "myButton". that way you can apply the function to all buttons with the above script. Just replace "#myButton" for ".myButton"
First, you should use .on('click', function() or .live('click', function() to resolve your one click issue.
You'll want to do something like:
<script>
$(function() {
$("#myButton").on('click', function() {
var a = 'somthing';
var b = 'something_else';
$.post('url.php', {param1: a, param2: b}, function(data) {
//data = url.php response
if(data != '') {
$("#loaddiv").fadeOut('slow').html(data).fadeIn("slow");
}
});
});
});
</script>
Then you can just put var_dump($_POST); in url.php to find out what data is being sent.
Try creating a function that would accept parameters that you want.
Like:
$(document).ready(function(){
$('.link').click(function(){
reload(p1,p2);
});
});
function reload(param1, param2){
$("#loaddiv").fadeOut('slow').load("reload.php?param1="+param1+"&param2="+param2).fadeIn("slow");
}
But by doing the above code your reload.php should be using $GET. Also you need to use class names for your links instead of id.
<script type="text/javascript">
// execute when document is ready
**$(document).ready(function() {**
**$("#myButton").click(function() {**
**$("#loaddiv").fadeOut('slow',function(){**
**$("#loaddiv").load("reload.php?var1=foo&var2=bar",function(){**
// content has finished loading, fade div in.
$("#loaddiv").fadeIn('slow');
});
});
});
});
</script>
$("#myButton").click(function() {
// get vars to use
var var1 = $(this).data('var1');
var var2 = $(this).data('var2');

Remove DIV only if empty

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/

Automatically refresh div content and immediately scroll down?

The thing is, I can do both, but I can't make them work immediately one after another, it does the first in the 1st clock, and the second in the 2nd clock. I've also tried with 1 div inside another but it's the same. Here's the code:
the script:
$(document).ready(function() {
$("#chatRoomSub").load("chatUpdate.php");
refreshId = setInterval(function() {
$("#chatRoomSub").load('chatUpdate.php');
var object = document.getElementById('chatRoom');
object.scrollTop = object.scrollHeight;
}, 5000);
$.ajaxSetup({ cache: false });
});
the body:
<div class='chatRoom' id="chatRoom">
<div class='chatRoomSub' id="chatRoomSub">
ainda nada foi escrito...
</div>
</div>
You need to use a callback function on the .load() which does the scrolling.
$("#chatRoomSub").load("chatUpdate.php", function() {
// scroll down
});
This way, the scrolling will occur immediately after the content is loaded.
You need to use call back function of jquery. Call back function is something that executes after event if i take an example .load("You code",function())..after loading your code, it will execute "code", it will execute function...

.load() jquery php General question

This is a general question, I have two pages, a main and a backgound function one (file.php)
Main page loads file.php passing variables:
$(document).ready(function() {
var page = $('#page').attr('value');
var user = $('#user').attr('value');
$('#DIV').load('file.php?user=' + user + '&page=' + page);
});
File.php queries database, inserts variables into more jquery stuff..
echos result...
The result on the main page is the desired one. If I fixe the variables in file.php (and load through browser) the script is fully functionnal and interactive.
My problem is as follows:
The file.php part of the main page is not interacive, i.e. when I click on it nothing happens, yet the 2 work fine idependently, together variables are passed, but the result is static.
My question, is this due to the .load() function? Should I be using $.ajax() type GET ...
Thanks in advance.
It sounds like you have jQuery behaviours attached to the DOM that are not being applied to the new content. This is because the new content is loaded after the DOM is ready (ie, after the load event fires).
This can be solved by using the .live jQuery function to attach events to a selector that will be applied to all elements, regardless of when they're added. E.g, instead of:
$('#button').click(function() { alert('hi'); });
Use:
$('#button').live('click', function() { alert('hi'); });
Is #DIV referring to:
<div id="DIV"></div>
Perhaps you should try this:
$(document).ready(function() {
var page = $('#page').attr('value');
var user = $('#user').attr('value');
// see the DIV below with the ID = "myId"
$("#myId").load("file.php?user=' + user + '&page=' + page", function(response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
$("#error").html(msg + xhr.status + " " + xhr.statusText);
}
});
});
<!-- empty containers with ID attributes -->
<div id="myId"></div>
<div id="error"></div>
If there is an error in the returned data, this will also tell you what the error is. Also, what does your debugger tell you?

Categories