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...
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.
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+"¶m2="+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');
QUESTION: What is the proper way to use .get() in conjunction with .one() (or .live()) so that an external php file is appended only once?
MOST RECENT EDIT:
solution
<script>
$(document).ready(function(){
$('.tree li a').one("click", function() {
var currentAnchor = $('.tree li a').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];
var query = "page=" + page;
alert ("page=" + page);
}
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
return false;
});
});
</script>
More Specifically:
I'm using Javascript and PHP to load some external PHP pages as sections in my main template.
I'm using a switch and append() so the included files keep appending. I need every file to be able to be appended ONLY ONCE. Here is the scenario as I'd like it to happen
1) downloads link is clicked
2) downloads.php appears
3) errors link is clicked
4) errors.php appears below downloads.php
5) downloads link is clicked again
6) page just scrolls up to top of downloads.php
I need the same functionality as the example on the documentation page of .one() where every div can be clicked only once.
I also looked at Using .one() with .live() jQuery and I especially liked the approach used in the accepted answer.
Iried using boolean flag as suggested below but all it did was limit my consecutive clicks on the same link to one. So if I click one link 1 multiple times it'll show page 1.php only once but if I click on link 1, then link 2, then link 1 again it will display page 1.php, then append page 2.php and append another page 1.php.
I'm starting to think that the setInterval is wrong and I may use .one() for the whole checkAnchor() function and bind it to the <a> tags. I tried this but it's not working either :(((
core.js - using .one()
var currentAnchor = null;
//$(document).ready(checkAnchor);
//Function which chek if there are anchor changes, if there are, sends the ajax petition checkAnchor
$("a").one("click", function (){
//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];
var query = "page=" + page;
}
alert ("hello");
//Send the petition
$("#loading").show();
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
}
});
The other thing I liked as an approach is adding the names of the pages to an array and then checking that array to make sure the page wasn't displayed yet. I managed to fill up an array with the page names using .push() but I hit a dead end when looking up for a value in it. If you have an idea how that's supposed to look like that'd be very helpful as well.
core.js
///On load page
var contentLoaded;
$().ready(function(){
contentLoaded = false;
setInterval("checkAnchor()", 300);
alert (contentLoaded);
});
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];
var query = "page=" + page;
}
alert ("hello");
//Send the petition
$("#loading").show();
alert (contentLoaded);
if (!contentLoaded){
$.get("callbacks.php",query, function(data){
$("#content").append(data);
$("#loading").hide();
});
alert (contentLoaded);
}
contentLoaded = true;
}
}
here is my
callbacks.php
<?php
//Captures the petition and load the suitable section
switch($_GET['page']){
case "4100errors" :
include 'template/4100errors.php';
break;
case "4100downloads" :
include 'template/4100downloads.php';
break;
}
?>
And my main file
4100.php
<?php
include 'template/header.php';
include 'template/4100menu.php';
include 'template/log.php';
include 'template/links.php';
include 'template/4100breadcrumbs.php';
?>
<div class="left-widget">
<div style="display:none; position:absolute; top:-9999; z-index:-100;">
</div>
<div id="side-nav-bar" class="Mwidget">
<h3>Contents</h3>
<ul class="tree">
<li><a href="#4100downloads" class="links" >Downloads</a> </li>
<li>Error Troubleshooting</li>
</ul>
</div>
</div>
<div id="content" style="margin-top:100px; margin-left:300px;">
<?
switch ($_GET['page'])
{
case "4100downloads": include 'template/4100downloads.php'; break;
case "4100errors": include 'template/4100errors.php'; break;
}
?>
</div>
</body>
</html>
4100dowloads.php
Downloads test page
4100error.php
Errors test page
Also you can look at the test page here http://period3designs.com/phptest/1/4100.php
"What is the proper way to use .get() in conjunction with .one() (or .live()) so that an external php file is appended only once?"
.one() and live() really have little to do with $.get. They're only for event handling.
If you intend to run the code every 50ms as you are, but want to replace the current content, then use .html() instead of .append().
$("#content").html(data);
This will overwrite the old content.
I assume you're aware of this, but just to be sure, your code is running at an interval because of this...
$().ready(function(){
setInterval("checkAnchor()", 50); // better--> setInterval(checkAnchor, 50);
});
If you only want it once on document load, then do this...
$(document).ready(checkAnchor);
Just use a boolean flag to determine if you loaded the data yet or not. Set it to false on page load, and just after the call to $.get set it to true. Then, wrap your $.get with an if (!contentLoaded) { $.get ... }.
That way you will execute the $.get only once.
BTW: $.one is used to bind an event to an element, that will execute only once and then unbind it self from it.
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();
});
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/