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);
}
Related
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.
What I'm trying to do is auto update a comment count on any prepended div that has been constructed by ajax. So basically replacing the ajaxed response div commentprint
success: function(data) {
$.each(data.posts, function(i, response) {
$("#homestatusid").prepend("<div id='commentprint"+response['streamitem_id']+"'>Comments "+response['num']+"</div>")[
}
});
I have a page called ajaxcommentcount.php. This is where the response would come from and replace commentprint. I just don't have any clue how to do it.
Okay I was able to send the data needed and retrived and updated the ajaxed div.
I added the following to the success
timer = setInterval(function() {
refreshCurrentTab(streamitem_id);
}, 5000); refreshCurrentTab(streamitem_id);
And then called the function in .load() passing the post id over to return and replace the div.
function refreshCurrentTab(streamitem_id)
{
$('#commentprint'+streamitem_id).load('ajaxcommentcount.php?var='+streamitem_id+'');
}
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/
Hello I am having trouble regarding div reloading when a new record has been added. What I wanted to do is to show first a loading image then after a record has been inserted it will reload the div.
$("a.follow").click(function(event) {
event.preventDefault();
$("#flash").show();
$("#flash").fadeIn(300).html('<img src="ajax-loader-transp.gif" />Loading Result.');
$.ajax({
//url: $(this).attr("href"),
success: function(msg) {
$("#results_div").load('http://localhost/<app_name>/index.php/<contoller>/index');
}
});
return false;
});
That's what I got to far when I'm trying the code it refreshes a whole physical of page on the div & not the desired div itself. . .
Sorry guys I am poor with jQuery and BTW this is in CodeIgniter.
Your problem is, that codeigniter obviously returns a whole html page. You have two choices:
Either return only a fragment (I don't know how to do this in CI) or use jQuery to parse out the div you want. This can be done with the following code, assuming that the div you want is named <div id="results_div">...</div>
$("a.follow").click(function(event) {
event.preventDefault();
$("#flash").show();
$("#flash").fadeIn(300).html('<img src="ajax-loader-transp.gif" />Loading Result.');
$("#results_div").load('http://localhost/<app_name>/index.php/<contoller>/index #results_div', function(){ $('#flash').hide(); });
});
Can you include the HTML with the #results_div div?
This is my best guess without html to work with:
$("a.follow").click(function(event) {
event.preventDefault();
// show the linke
$("#flash").fadeIn(300).html('Loading Result.');
//ajax load the 'mini div' result -- i guessed that this url pulls back the div you want
$("#results_div").load('http://localhost/<app_name>/index.php/<contoller>/index', function(data, text, xhr){
$('#flash').fadeOut("fast");
});
});
Hi everyone I have been working on this particular problem for ages by now,plz help.
I have looked at jQuery: Refresh div after another jquery action?
and it does exactly what I want but only once! I have a table generated from db and when I click on delete it deletes the row and refreshes the div but after which none of my jquery functions will work.
$('#docs td.delete').click(function() {
$("#docs tr.itemDetail").hide();
var i = $(this).parent().attr('id');
$.ajax({
url: "<?php echo site_url('kt_docs/deleteDoc'); ?>",
type: 'POST',
data: 'id=' + i,
success: function(data) {
$("#docs tr.itemDetail").hide();
$("#f1").html(data); // wont work twice
//$("#docs").load(location.href+" #docs>*"); //works once as well
}
});
});
in my body I have
<fieldset class='step' id='f1'>
<?php $this->load->view('profile/docs_table'); ?>
</fieldset>
profile/docs reads data from db. <table id='docs'>....</table>
and my controller:
function deleteDoc() {
$id = $_POST['id'];
$this->load->model('documents_model');
$del = $this->documents_model->deleteDocument($id);
return $this->load->view('docs_table');
}
Thanks in advance!
Are you removing any expressions matching $('#docs td.delete') anywhere? If so, consider using $.live(), which will attach your function to ALL matching elements regardless of current or in the future; e.g.
$('#docs td.delete').live('click', function() {
// Do stuff.
});
http://api.jquery.com/live/
Try using bind() instead of click(). The click() method won't work on dynamically added elements to the DOM, which is probably why it only works the first time and not after you re-populate it with your updated content.
You should just have to replace
$('#docs td.delete').click(function() {
with
$('#docs td.delete').bind('click', function() {
Are you replacing the html elements that have the events on them with the data your getting through ajax? If you end up replacing the td.delete elements, then the new ones won't automatically get the binding.