Reload html page with AJAX - javascript

I have a very simple html page with one table that I would like to reload in the background every 5 seconds. In the background means that solution <meta http-equiv="refresh" content="5"> can not be accepted, because the user can observe reloading process then.
I tried the code below, but I observed that RAM usage was quickly raising and after 2-3 minutes firefox browser consumed 70-80% of available memory:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function autoRefresh_div()
{
$("#employee_table").load("index.html");// a function which will load data from other file after x seconds
}
setInterval('autoRefresh_div()', 5000); // refresh div after 5 secs
</script>
Could you please suggest something more efficient?
EDIT:
I forgot to add that in the body of html I have:
<div id="employee_table">
<table>
...
</table>
</div>
And what I wasn't sure is that I use load("index.html") so I'm loading whole page instead of just a div...?

you can also use $.ajax instead of $("").load("url");
as it will only replace the content of the given element in success function means when the AJAX request is successful, so flickering can be prevented.
function autoReload() {
setTimeout(function() {
$.ajax({
url: '/index.html',
success: function(data) {
document.getElementById("employee_table").innerHTML = data;
}
});
autoReload(); // calling again after 5 seconds
}, 5000);
}
autoReload(); // calling the function for the first time
or you can also use $.get
$.get("index.html", function(data, status){
if(status == "success"){
document.getElementById("employee_table").innerHTML = data;
}
});
$.ajax() is the most configurable one, where you get fine grained control over HTTP headers and such. You're also able to get direct access to the XHR-object using this method. Slightly more fine-grained error-handling is also provided. Can therefore be more complicated and often unecessary, but sometimes very useful. You have to deal with the returned data yourself with a callback.
$.get() is just a shorthand for $.ajax() but abstracts some of the configurations away, setting reasonable default values for what it hides from you. Returns the data to a callback. It only allows GET-requests so is accompanied by the $.post() function for similar abstraction, only for POST
.load() is similar to $.get() but adds functionality which allows you to define where in the document the returned data is to be inserted. Therefore really only usable when the call only will result in HTML. It is called slightly differently than the other, global, calls, as it is a method tied to a particular jQuery-wrapped DOM element. Therefore, one would do: $('#divWantingContent').load(...)
It should be noted that all $.get(), $.post(), .load() are all just wrappers for $.ajax() as it's called internally.
More details in the Ajax-documentation of jQuery: http://api.jquery.com/category/ajax/
Hope this will help you.

Related

How can I retrieve data from 'any' ajax request being completed using jQuery? [duplicate]

I have a page where I can insert some javascript / jquery to manipulate the output. I don't have any other control over the page markup etc.
I need to add an extra element via jquery after each present on the page. The issue is that the elements are generated via an asynchronous call on the existing page which occurs after $(document).ready is complete.
Essentially, I need a way of calling my jquery after the page has loaded and the subsequent ajax calls have completed. Is there a way to detect the completion of any ajax call on the page and then call my own custom function to insert the additional elements after the newly created s ?
Unfortunately this doesn't apply since it seems the OP isn't using $.ajax() or any jQuery ajax method for actually loading content, but leaving it here in case future googler's are doing this.
You can use any of the global ajax events that meet your needs here, you're probably after $.ajaxComplete() or $.ajaxSuccess().
For example:
$(document).ajaxSuccess(function() {
alert("An individual AJAX call has completed successfully");
});
//or...
$(document).ajaxComplete(function() {
alert("ALL current AJAX calls have completed");
});
If you want to run just some generic function then attach them to document (they're just events underneath). If you want to show something in particular, for example a modal or message, you can use them a bit neater (though this doesn't seem to be what you're after), like this:
$("#myModal").ajaxComplete(function() {
$(this).fadeIn().delay(1000).fadeOut();
});
This example just shows and hides elements at the start and end of ajax calls using jQuery:
$("#contentLoading").ajaxSend(function(r, s) {
$(this).show();
$("#ready").hide();
});
$("#contentLoading").ajaxStop(function(r, s) {
$(this).hide();
$("#ready").show();
});
#contentLoading is an gif image progress indicator.
As i could understand, you are using some jQuery's Ajax function in your ready handler. So you could just pass it another function, which will be invoked after your Ajax function gets response. For example
$(document).ready(function(){
$("#some_div").load('/some_url/', function(){
/* Your code goes here */
});
});
You could rewrite the send() function of the XMLHttpRequest object.
See a solution for doing just so using pure Javascript here.
You could use .live()/.delegate().

jQuery: get() is slower compared to load()

Obvious question - why?
I need to get from external page table cell, and then inject it to the current page. Complex selectors are used.
This is with .load():
$('#check').load('https://bla-bla-bla .small:contains(Something)+.small:lt(1)');
This is with .get():
function showGetResult()
{
var result = null;
var scriptUrl = "https://bla-bla-bla";
$.get(scriptUrl, function(data) {
result = $(".small:contains(Something)", data).next().html() || "Error";
$('#check').append(result);
});
}
load() get data faster by average 1-2 seconds. But I like get() - since I can have string result, not an object.
Can someone explain why load() works faster?
Because I'd love to find the answer to this myself, I figured it would be nice to provide some resources to help:
AJAX jQuery.load versus jQuery.get:
First of all those two functions are completely different. The 'load' function works with selectors and loads the result of AJAX call inside the selected group and the callback is to handle the "oncomplete" event of the call; while the $.get function is more general and the callback handles the success response of AJAX call where you are free to define any behavior you want. And you can find all this information just by looking at the documentation and specification of the jQuery framework.
Difference between $.ajax() and $.get() and $.load()
$.get() is just a shorthand for $.ajax() but abstracts some of the
configurations away, setting reasonable default values for what it
hides from you. Returns the data to a callback. It only allows
GET-requests so is accompanied by the $.post() function for similar
abstraction, only for POST
.load() is similar to $.get() but adds functionality which allows you
to define where in the document the returned data is to be inserted.
Therefore really only usable when the call only will result in HTML.
It is called slightly differently than the other, global, calls, as it
is a method tied to a particular jQuery-wrapped DOM element.
Therefore, one would do: $('#divWantingContent').load(...)
Seems $.get and $.load both use $.ajax functionality, but in different ways. Perhaps the performance difference lies in the time it takes to parse the returned data?
Maybe the real question is how long do each of these take to send the request to the external URL (a "ping" time), and then how does that compare with processing the returned data?

Javascript window.location calls getting lost?

I am having some trouble with a bit of code. I have a function that does some stuff to some data, calls a remote system (activating a script on that system and passing in the data), and then makes another call to the same system to activate a different script (which acts on the data saved above). The problem is that the 1st call to the remote system appears to get lost in the execution.
This is being run in Safari, uses jquery; the function is tied to a button click, which is defined in the javascript code with an onclick function (i.e. it is not defined in the html button definition).
Here's a rough breakdown of the function (cleaned out for viewing purposes - I hope I left enough to make it clear):
function compareJSON() {
// loop through the objects, testing and changing data
// ...
dataSession=({ //build object for output });
$.each( dataSession.chapters , function( indexC, value ) {
//compare objects to some others, testing and changing data
});
// ...
//Call remote script on other system
urlString="url://blah.dee.com/Blar?script=SaveJSON&$JSONobject=";
window.location= urlString + JSON.stringify(dataSession);
//Call remote script on other system
window.location="url://blah.dee.com/Blar?script=EditJSON";
}
The last three lines of code are the two calls. It uses the window.location to actually trigger the remote system, passing the data through the URL. But I need BOTH scripts to get called and run. It appears that only the LAST script in the sequence ever gets run. If I switch them around it remains whatever is in last place.
Is there something about the window.location that doesn't actually process until the end of the function?
This script actually used to be a series of separate function calls, but I figured I was running into asynchronous execution that was causing the various script calls to not register. But once I put the code into this single function, it was still happening.
Any clues would be helpful.
Thanks,
J
Modifing the value of window.location is reserved exclusively for instances in which you'd like to cause a browser redirect.
It looks like you want to trigger a page request instead. You say you already have jQuery loaded, if so, you can trigger such a request using jQuery.get or a similar function.
For example:
// Loads the myscript.php page in the background
$.get('myscript.php');
// You can also pass data (in the form of an object as the second argument)
$.get('myscript.php', { name: "John", time: "2pm" });

order of events on click on <a> tag

So I have a normal link on my website, and I want to add tracking for it. I could envision a bunch of ways to do this, but I've settled on this as being really easy by writing a small jquery function, and dropping a small snippet in my tags:
click me!
javascript:
function saveClick(someparamhere){
$.ajax({
url: "somepage.php",
data: {param:someparamhere}
});
}
Now, I know my syntax might be bad, I'm just asking about the overall concept here. When you click the link, I want javascript to issue the call to saveClick which immediately makes an ajax call. There's no success handler because I don't really care if or what gets returned. I'll just have somepage.php log the event. Then, after all of that, I want the tag to go to it's href.
Is that the case? Will the ajax call be issued before the document goes to the other page? Will this work in all cases?
Has anybody ever done something like this? Any experience would be appreciated ....
If you want to make sure the AJAX call goes through you could do:
click me!
$('[data-parameters]').bind('click', function (event) {
//cache this element to use in AJAX function
var $this = $(this);
//prevent the default naviation
event.preventDefault();
$.ajax({
url: "somepage.php",
data: {param:$this.attr('data-parameters')}
success : function () {
//now navigate to the requested page
location = $this[0].href;
}
});
});
UPDATE
$.ajax() exposes a timeout function:
timeoutNumber
Set a timeout (in milliseconds) for the request. This will override
any global timeout set with $.ajaxSetup(). The timeout period starts
at the point the $.ajax call is made; if several other requests are in
progress and the browser has no connections available, it is possible
for a request to time out before it can be sent. In jQuery 1.4.x and
below, the XMLHttpRequest object will be in an invalid state if the
request times out; accessing any object members may throw an
exception. In Firefox 3.0+ only, script and JSONP requests cannot be
cancelled by a timeout; the script will run even if it arrives after
the timeout period.
So you could set a timeout and an error function that mimics the success function. The documentation does state that: it is possible for a request to time out before it can be sent but if your timeout is a very small (maybe zero) delay then it could reduce the lag between the user clicking the link and the browser loading the new page.
I simply wouldn't do that... it could bring to situation your onclick event isn't fired.
I think it would be better to call a javascript function on click that does your ajax call and then bring the user to the target page.
You can do this, for example, this way:
...
your javascript function then, shall be something like:
myfunc(paramofpageclickhere) {
//do ajax call
saveClick(someparamhere);
//go to target page
location.href = "target.htm";
}

Detecting When Javascript is Done Executing

Is there an event in javascript that I could bind some sort of listener to that will tell me when all javascript/jQuery/Ajax is done executing on the page? The page will not be loading/unloading/reloading, etc between the time the execution begins and the time that I need the listener to "listen", so those events don't work. The page literally is not doing anything. The button is clicked and some javascript functions fire which contain Ajax calls to web services. After all have finished, I want to change window.location. But window.location is changing before the web services have finished in my case.
Currently using setTimeout to achieve this, but as sometimes the code needs more time to run than normal, sometimes the window.location is firing before all the other javascript has finished. Simply put
<input type = "button"... onclick="doThis();";
function doThis() {
try{
//Contains AJAX calls to web services which is mainly what screws up my timing since it may still be trying to execute stuff when the redirect statement happens
}
catch (e) {
}
//Currently doing setTimeout(redirect, 10000);
//Would like to simply detect when all of the above is done and then redirect.
}
Edit: Left out a crucial piece of info. The AJAX calls are in a for loop. The use of variables and success callbacks hasn't been working so well for me as by the time my success callback is executing, my variables have taken on new values in the for loop.
What you are trying to achieve is a classical concurrent programming problem. It is solved by the use of a barrier.
To put it simply, you need to:
Count how many calls you've done.
Set a callback on all AJAX completion events.
Make that callback decrement the number of calls.
The callback checks whether the number of calls has reached zero or not. If yes, then your final code (here, redirect) is called.
The actual implementation is left as an exercise to the reader :)
Hint: embed AJAX calls into a function that handles all counter incrementation and callback setting.
What I do:
Create a variable that represents the number of outstanding AJAX calls.
Before making an AJAX call, increment the variable.
At the end of the code that completes an AJAX call, call a function (e.g. ajaxComplete).
ajaxComplete should decrement the count. When it reaches zero, you know all your calls are complete.
Assuming you're using jQuery.ajax, it sounds like you're looking for ajaxStop.
Why don't you try using something like the Underscore library's after function in the callbacks?
var done = _.after(3, function() {
window.location = 'http://example.com';
});
$.ajax({
url: '/tic',
success: function() {
done();
}
});
$.ajax({
url: '/tac',
success: function() {
done();
}
});
$.ajax({
url: '/toe',
success: function( data ) {
done();
}
});
You should check for the response from AJAX call, and only in that response do redirect. This way you will avoid doing redirect while AJAX was still executing.

Categories