jQuery Auto refresh div messing up - javascript

I have a script that auto-refreshes a certain div on the page (That I got from another post on here)
<script type="text/javascript">
var auto_refresh = setInterval(
function(){
$('#refresh').load('index.php?_=' +Math.random()).fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>
...............
<div id="refresh">
<!-- Some PHP Code -->
</div>
This refreshes, however when it does, I takes the entire html document and puts it into the div. Like this:
As you can see, the refreshed div (the one marked in red) is getting the body shouved into it. Any ideas???

You are loading entire page to the div.
Modify the code to use only part of the document that is fetched:
<script type="text/javascript">
var auto_refresh = setInterval(
function(){
$('#refresh').empty();
$('#refresh').load('index.php?_=' +Math.random()+' #refresh').fadeIn("slow");
}, 10000); // refresh every 10000 milliseconds
</script>

First off, you are loading the entire page into the divider, thus causing the file to reload entirely. Instead, you should be having the Recent Posts divider load from a single file, even on the first page load. Then have that consistently refresh over time.
Secondly, you should be transferring as little data as possible from your server to your clients. At most, you should use a minimalistic checksum of sorts (number of messages, for instance) to confirm that the client and server are synced up.
Lastly, if you choose to use this format, aim to transfer your data in something such as JSON or XML and have the client display it on the page. Transferring the styled HTML increases network overhead and is not the best practice.

Related

Trying to refresh div inside Iframe

I have a section of my site im working on where i have a certain div, the div "comments" needs to be checked for blank comments being posted and remove them, it works fine the first time but after the div is refreshed it stops working. I'm trying to get this script to reload every second along with the div so the results stay consistent. Here are my 2 scripts:
<script type="text/javascript">
function doRefresh(){
$("#comments").load("comment.txt");
}
$(function() {
setInterval(doRefresh, 1000);
});
</script>
<script>
setTimeout(refreshData, 1000);
function parent()
{ $(".comment_name:empty").parent().hide()};
refreshData();
</script>
For future reference you should have a look into websockets. This will enable you to have data refresh as it is entered from one browser to another and will always keep it up to date without refreshing.
Here is a reference for you to get started. https://developer.mozilla.org/en-US/docs/Web/API/WebSocket
It is a starting point and will help you a lot in future for dynamic content on multiple end points.

JavaScript Timers and Page Navigation

Hopefully a simple question; if I create a timer using JavaScript embedded within my page, and I then navigate away from that page, will the timer be automatically cancelled or will it continue to run?
EDIT
Expanding the question, if that page were to perform a post-back (in my case, this is ASP.NET Forms), and the script is rendered as a part of the page markup, would the original timer created when the form is first displayed be cancelled during that post-back or would a second timer be created?
Example (rough typed):
<body>
...
<script type='text/javascript'>
function doSomething() { ... }
x = setInterval(doSomething(), 60000);
</script>
...
<button type="submit" />
...
</body>
Following the post-back, a new timer will be created as a result of the page being re-rendered, how many timers are now running (assuming the post-back was within the interval specified by the timer)?
It'll be automatically cancelled. JavaScript code is executed within the context of a page.
Think about a page like an application. Switching to other page is like closing an application and opening a new one. This also applies to a full page refresh (i.e. when you press F5).

Auto refresh JS with appendchild command that grabs data from an external file

I am creating a chat system and I am using html/php/jquery.
How can I append a child with data from an external file to a div using javascript auto refresh feature?
The code that I have:
<script>
var auto_refresh = setInterval(
function()
{
$('#messages_box').load('refresh_messages.php');
}, 1000);
</script>
The code above refreshes the whole DIV with data grabbed from the mentioned document.
<script>
var auto_refresh = setInterval(
function()
{
var textnode=document.createTextNode("Water");
document.getElementById("messages_box").appendChild(textnode);
}, 1000);
</script>
And the code above, appends the text to the div I want.
I want to "combine" this two and obtain the following result:
Auto-refresh an external php file every second and if there are new results (messages in my case) the messages_box DIV should be updated with the results using the appendchils JS method.
I want to create a chat messaging system that will grab messages if a new result is encountered when loading the external php fild. I want to use the appendchild method, because by doing this I will practically add a new child to the div, not refresh the whole div. I absolutely need to append stuff, not to load the whole DIV again.
It seems to me that what you are looking for is an AJAX request.
Here's how I would set this up:
Have a database set up to store messages
Have a PHP file with various functions to both retrieve and send messages to/from the database.
Have another PHP/HTML file with javascript that creates an AJAX request to the other PHP file on a regular basis.
There is tons of documentation on how to create ajax requests with pure javascript, but I personally prefer to used the jQuery .ajax() function.

Trigger Third-Party Javascript from Event

I run an eCommerce website. On our order confirmation page we run a third-party javascript that automatically executes an optional survey.
The problem with the survey is that it takes twenty seconds to execute and slows down the rendering of the crucial 'Order Complete' page.
I am wanting to prevent loading of this script until the customer clicks a button.
Ideally, the page will load without executing the script. There will be some text on the page that says, "Would you like to take a survey? If yes, click here." Then the page will call the third-party javascript to execute the survey code.
Below is the third-party javascript. The first script tag just collects variables, and the second script tag actually runs the survey code.
<script language="JavaScript">
// var passin_x =; //comment out to default center or adjust horizontal position by pixel
// var passin_y =; //comment out to default center or adjust vertical position by pixel
var orderId='##order_id##';
// var z_index =; //default 9995
var cartTotal='##purchase_total##';
// var billingZipCode=;
// Pass up to 5 products from customer shopping cart
//var productsPurchased= 'URL=^SKU=^GTIN=^PRICE=|URL=^SKU=^GTIN=^PRICE=|URL=^SKU=^GTIN=^PRICE=|URL=^SKU=^GTIN=^PRICE=|URL=^SKU=^GTIN=^PRICE=';
</script>
<script type="text/javascript" src="https://eval.bizrate.com/js/pos_xxxxx.js">
</script>
How can I dynamically load the script after the click event?
I used jQuery.getScript to dynamically load the script after the click event.
Specifically, I used the technique shown here:
http://www.tutorialspoint.com/jquery/ajax-jquery-getscript.htm
Which looks like this:
$(document).ready(function() {
$("#driver").click(function(event){
$.getScript('/jquery/result.js', function(jd) {
// Call custom function defined in script
CheckJS();
});
});
});
Why would you want to do this anyway? This will slow down your site for calling an external link to fire off your js and if anything happens to the external site then your js functions will be voided and the site may break. This is not a good coding practice you should obtain a copy of the js file and store it locally within your hosting server...
This is just my opinion anyway.
-Epik-

Preloader for dynamic content

I have dynamic page which takes about 8 seconds to load searched data.
Problem is, all browsers remain on old page for those 8 secs & show dynamic page only after it
loads completely.
What I want is preloder image to be shown to the customers until second page gets load.
How can I achieve this?
Thanks
I assume you are loading the second page through AJAX. If so, you'll only be able to display the results after the asynchronous call returns.
However, nothing prevents you from making changes to the page before sending off the AJAX request. The basic structure will be:
var preload = $('<div></div>').text('I am preloading!').insertAfter('somewhere');
$.get(..., function() {
preload.remove();
// insert your real content, received from this AJAX request
});
$('<div id="busy">Loading...</div>')
.ajaxStart(function() {$(this).show();})
.ajaxStop(function() {$(this).hide();})
.appendTo('body');
That's all!
You may want to add some style to #busy tag, but this you can do with CSS.

Categories