How to refresh mysql posts every 1 second - javascript

I use ajax to save user posts/comments into a mysql table without page refresh.
First: I have this <div id="posts-container"></div>
Second: I've tried using Jquery load() to loop in table and echo the posts, with the following code:
var auto_refresh = setInterval(function() {
$('.posts-container').load("refresh_p.php").fadeIn();
}, 0 );
But it doesn't work, page refreshes but content doesn't load, anybody knows why?
Third: If i copy the code that contains refresh_p.php and paste into the data gets loaded successfully. A little weird? Yes. Hope get any help :)
EDIT:
I fixed it, the problem was in refresh_p.php it was expecting the parameter 'profile_id'
i modified the function to this:
1: profile.php
search_user = document.getElementById('user_from').value;
var auto_refresh = setInterval(function() {
$('.posts-container').load("refresh_p.php?search_user="+search_user).fadeIn();
}, 5000 );
2: refresh_p.php
$profile_id = $_GET['search_user'];
All good, but now the whole page refreshes every 5 seconds. I just want the div 'post-container' to refresh.
I've used this function before to refresh a chat box and it worked, only refreshes the div i wanted to. but here it refreshes the entire page.

Don't use setInterval. Do recursive calls on jQuery load complete, this way you make sure that calls are sent one AFTER another, not at the same time.
Try this:
var auto_refresh = function () {
$('.posts-container').load("refresh_p.php", function(){
setTimeout(auto_refresh, 800);
}).fadeIn();
}
auto_refresh();
Also, .fadeIn() only works the first time, after that you have to hide the div before showing it again.
Demo: http://jsfiddle.net/P4P9a/1/ (might be slow because it is loading an entire page).
LE: As I think you are not returning an HTML page you should use $.get instead of $.load .
$('.posts-container').get("refresh_p.php", function(data){
$(this).html(data);
setTimeout(auto_refresh, 800);
}).fadeIn();

var auto_refresh = setInterval(function(){
$('.posts-container').load("refresh_p.php").fadeIn(50);
},1000);
Changed the interval from 0 (which would just create a crazy load...) to 1000ms (1 second). Should work if your path is correct.

Make sure your interval is long enough for your requests to finish. Also think about less real-time options, such as sending an array of messages every 15 seconds, showing them one after another on the client side. Optimize your server side for quick response using caching and also think about using json data and client side templating instead of html responses.

Related

Refresh razor page without reload using javascript/ jquery in asp.net core

I have one input and script to reload table in my page. In the input if I insert 1000 I want to reload page every second, without clicking any buttons.
This is what I tried :
<input id="txtRefresh" />
<script>
document.redy(function () {
$('tblRefresh').load();
setInterval(function () {
$('#tblRefresh').load();
}, 'txtRefresh');
});
</script>
Its cshtml razor page.
What I want to do is to insert the value of seconds in the input andrefresh the page based of the of the inserted value, without submiting any data.
Is it possible to do this? Any suggestions?
Thanks in advance!
UPDATE
I inserted this script:
<script>
document.ready(function () {
$('#refreshDIV').load('url/url/url');
setInterval(function () {
$('#refreshDIV').load('url/url/url');
}, $('#txtRefresh').val());
});
</script>
But it gaves me error!
refreshDIV is a div that I want to refresh
txtRefresh is the input from I insert the seconds
you can try this:
$(document).ready(function(){
var timeout = $("#txtRefresh").val();
setTimeout(timeout, function() { location.href=""; });
});
but each time you will reload the page you will lose, the input.
You could send it through querystring like this:
location.href="?timeout="+timeout
and populate the input server side
This is just a string:
'txtRefresh'
If you want to get the value of that element, it would be more like this:
$('#txtRefresh').val()
You also have a typo in document.ready and in your first #tblRefresh selector (missing the #), and you aren't supplying .load() with the URL you want to load. All together you appear to be trying to do this:
$(document).ready(function () {
$('#tblRefresh').load('/some/url');
setInterval(function () {
$('#tblRefresh').load('/some/url');
}, $('#txtRefresh').val());
});
A couple things to note:
The value /some/url is of course a placeholder in this sample code. Whatever URL you want to use in your application is up to you.
Calling .load() will place the entire response of that URL into the target element. If you want only a subset of that response, you can add selectors to .load(). For example:
$('#tblRefresh').load('/some/url #someElement');
This would tell .load() to grab all the content from /some/url and then only select from it the content of #someElement to place in #tblRefresh. The performance could still potentially be slow as all of the content from the URL is still downloaded. To address performance or for finer control over data, consider returning JSON data from the server and using .ajax() to fetch that data instead of using .load() to reload all of the HTML (when only the data has changed).

Javascript - form submit and refresh only once

Currently I have a script that refreshes my 'chat' page every 10 seconds, as it retrieves the chat from a database. However at the moment once the page is loaded I have to wait 10 seconds (or the seconds i specify in the current js) for the chat to show.
I am not sure how to go about making the chat load initially on window.onload just once, and then every 10seconds. I've tried quite a few ways but they just lead to the onload constantly executing.
current js
<script>
window.onload = function() {
window.setTimeout('document.chatMsgListForm.submit()', 10000)
}
</script>
I gave this a shot too
<script>
var done;
window.onload = function(){
while(!done) {
document.forms['formChat'].submit()
done=true;
}
}
window.onload = function() {
window.setTimeout('document.formChat.submit()', 10000)
}
</script>
But no luck unfortunately.
Thank you
You should to look at using AJAX polling or long polling with WebSockets or something else.
Look this answer and this article, for example.

Execute jQuery after Other JS file Dynamically loads content

I'm working to modify some content which is dynamically loaded via another script(let's call is script #1) onto my site. Script #1 loads some markup and content and I've been using the setTimeout() function to call my script (Script #2) using a delay of a few seconds, in order to wait to be sure that Script #1 has executed and the content is present in the DOM.
My issue is that Script#1 has different loading times, based on the server load and can be slow or fast depending on these factors, and right now, playing it safe with setTimeout() I'm often left with a second or two where my scripts are still waiting to be fired and Script #1 has already loaded the content.
How can I execute my script as soon as Script#1 successfully loads it's dynamic content?
I've found this post which does seem to address the same issue but using the setInterval function as #Matt Ball has laid out there doesn't work at all for some reason. I'm using the code below where 'div.enrollment' is meant to find in the DOM which is dynamically loaded and execute..
jQuery(window).load(function ($)
{
var i = setInterval(function ()
{
if ($('div.enrollment').length)
{
clearInterval(i);
// safe to execute your code here
console.log("It's Loaded");
}
}, 100);
});
Any help on guidance on this would be greatly appreciated! Thanks for your time.
It seems that the healcode.js is doing a lot of stuff. There is a whole lot of markup added to the <healcode-widget> tag.
I would try to add another tag with an id inside and test for its existence:
<healcode-widget ....><div id="healCodeLoading"></div></healcode-widget>
Test in an interval for the existence of healCodeLoading inside <healcode-widget>: (Assuming jQuery)
var healCodeLoadingInterval = setInterval(function(){
var healCodeLoading = jQuery('healcode-widget #healCodeLoading');
if (healCodeLoading.length == 0) {
clearInterval(healCodeLoadingInterval);
// Everything should be loaded now, so you can do something here
}
}, 100);
healcode.js should replace everything inside <healcode-widget></healcode-widget> during init. So, if your <div>-element is no longer inside, the widget has loaded and initialized.
Hope that helps.
If you just want to load some markup and content and then run some script afterwards, you can use jQuery. You should use something like the following in script#1 to run a function in script#2
$.get( "ajax/test.html", function( data ) {
// Now you can do something with your data and run other script.
console.log("It's Loaded");
});
The function is called, after ajax/test.html is loaded.
Hope that helps

Autorefresh content

I am using Dreamweaver CS5. I have a SQL database set up with weather descriptions that have been set up to change at a set interval, however they do not refresh on their own unless the page is physically refreshed. I have users that are logged in for hours at a time so that doesn't exactly work.
I know I can fairly easily set a refresh for the entire page, but I'd prefer not to do that.
I would like to just used some kind of javascript or jquery to auto refresh that section of code.
This is the section of code I want to refresh:
<?php echo ucfirst($row_Recordset1['description']); ?>
I saw this as a solution, but I am not sure how to implement this to work for me, or if there is a better solution all together.
<script type="text/javascript">
function refreshDiv() {
gg1.refresh(getRandomInt(0, 100));
}
$(document).ready(function () { setInterval(refreshDiv, 5000); });
</script>
You need to reload the div's content over AJAX. Since you are using jQuery, you can easily do something like:
$(document).ready(function () {
setInterval(function(){
$('#divid').load( '/url' );
}, 5000);
});
You can read more about .load here
You need to use
set timeout()
JavaScript function. And inside that function you need to refresh your div content using jquery Ajax. Script is pretty simple and will give you desired result. For reference check w3schools and jquery Ajax

Javascript won't load using jQuery Mobile with navigation-geolocation

I am having an issue with jQuery Mobile, javascript and get geolocaton.
I am currently using following to get the code to load, when I enter the page:
$(document).on('pageinit', function(){
If the user has set visibility to visible, a div with the ID visible is shown, this I use to call the geolocation the first time:
if ($('#visible').length) {
navigator.geolocation.getCurrentPosition(sucessHandler, errorHandler);
}
After this I call the geolocation every 20th second:
setInterval(function() {
if ($('#visible').length) {
navigator.geolocation.getCurrentPosition(sucessHandler);
}
}, 20000);
My issue is, if I leave the page for one of the subpages, and return to this page, these codes won't run again. I have tried the following to load the javascript, instead of pageinit:
$(document).on('pagebeforeshow', '#index', function(){
and
$(document).on('pageinit', '#index', function()
I tried loading it in the body of the index as well.
Any help would be greatly appreciated =)
Regards, Fred
Firstly, you may want to consider replacing navigator.geolocation.getCurrentPosition() with navigator.geolocation.watchPosition(). This will call your success or error handler functions each time the device receives a position update, rather than you needing to ping it every 20 seconds to see if it has changed.
With regard to page changing, so long as you’re using a multi-page template, then the handler function should get called while navigating to and from any sub-pages.
Here’s a JS fiddle illustrating this
Hope this helps!

Categories