refresh <head> container of the website using ajax - ajax

Is there a way to refresh only a part of a website using ajax or a similar technique? The visitor must not notice the refresh.
What I want to do is refresh the <head></head> container of a website only one time after the website has been fully loaded using ajax?

Generally speaking, yes, you can modify <head> after the page has loaded. This can be used to quietly load remote scripts, or similar actions.
Without more specifics of what you're trying to do, here's some generic example code:
window.onload = function() {
//Send your ajax request, with success callback ajaxCallback
}
function ajaxCallback(response) {
//Parse response to create HTML tags you want inserted into <head>
var newHTML = response.newHTML;
document.getElementsByTagName("head")[0].appendChild(newHTML);
//If you want to completely replace the contents of <head>,
//you can use .innerHTML instead of .appendChild
});

Related

struts2 ajax redirect

i develop a app that is built with struts2+tiles+dojo (for the ajax part), and i have the following demand: At every 2 seconds i have to check a table from the DB, if certain conditions are met, i have to redirect the user to a special page.
The way that i solved this problem was creating a struts2 actions which`s check the table and render as a response something like :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<script>
window.location= '<s:property value="url"/>';
</script>
</body>
</html>
and this page is accesed via a ajax call like:
<sx:div href="%{ajaxUrl}"
updateFreq="1200"
cssStyle="float:right"
id="live"
loadingText="Loading..."
executeScripts="true"
parseContent="false">
</sx:div>
and this is how i accomplish the redirect.
I`m sure that there has to be an more elegant and optimized solution.
Any ideeas ?
Use the struts2-json-plugin on the action which is the target of ajaxUrl. I don't use the sx tags, I just use JS (with jQuery, the normal library not using any struts2 plugin). Any ways use JS to asynchronously call your action every 2 seconds with JS (or framework of choice) and you will get back the url as a json string, and you will then redirect to that new url if the string is not empty (or you could return back many variables perhaps, perhaps containing some of the conditions found in the DB and showing them on the page and redirect according to those status variables).

How to load script and html content from a url using jquery?

I have a html page in which i have a div where i need to load content from another page, which contains javascript and html. if i load as plain html, the html doesn't work.
so is there anyway make the javascript to work the way it has to and the html too when loading it using ajax.
<script type="text/javascript">
$(document).ready(function(){
$("#myDiv").load("myPage.html");
});
</script>
If I'm reading this properly, then you might not be-able to do this, there are all sorts of mechanisms to stop javascript from accessing data from other places, due to security concerns.
However, can you not simply just use an IFrame ?
$(document).ready(function(){
$('#result').load('ajax/test.html'); });
else try this
$('#result').load('ajax/test.html', function() {
alert('Load was performed.'); });

How to refresh a iframe when the page changes? With AJAX?

Is it possible to refresh an iframe whenever the page changes? (The page within the iframe - not the page the iframe is on) I want to have an iframe show a page which is being developed, then whenever the page is changed/updated I want the iframe to refresh so it shows the newer version. Hope that makes sense. :P
Or would it be better to use something else instead of an iframe? Are iframes outdated now?
Only because I find this interesting... using jQuery:
<iframe id="someiFrame"></iframe>
<script type="text/javascript">
var page = '/some/page/on/this/server.html', lM;
function checkModified(){
$.get(page, function(a,a,x){
var mod = x.getResponseHeader('last-modified');
if(lM != mod){
lM = mod;
$('#someiFrame').attr('src', page);
}
}
}
setInterval(checkModified, 5000); // every 5 seconds
</script>
That will poll the page every 5 seconds (incredibly wasteful but if it's on a local dev machine, so what?) and reload the iframe only when the page is updated :)
Note that the iFrame MUST be on the same domain as the parent page.
Do you have access to the page that's being modified? If so, why not just add a refresh meta tag to the page's HEAD that will then update your iframe at whatever interval you set. The following tag produces a 5-minute refresh and it won't matter if your iframe is cross domain:
<meta http-equiv="refresh" content="300" />

Is there a way of making normal links automatically load through ajax, rather than normally?

I haven't explained this well.
But what i mean is, if I have an ajax script that loads the content of a page in a DIV element, through the function 'loadpage('whatever.php');, instead of going around manually doing this to all links, is there a way of having a script that automatically makes all regular links load through that ajax function?
Like on Facebook, your profile loads through ajax, yet if you look at their code, they just have a regular link to the profile.
Cheers!
Sure, you can do it with jQuery.
This script goes through the document, finds every anchor element and binds an event handler to the click event of each. When the anchor element is clicked, the event handler finds the href attribute and loads that page into #targetDiv (you can call this div whatever you want, of course).
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
$("#targetDiv").load(($(this).attr("href") + " body");
return false;
});
});
</script>
...
<!-- In your document body, this is the div you'd load the pages into. -->
<div id="targetDiv"></div>
You can use JQuery for this (if I understand your question right).
First you can make the function loadpage() as follows:
function loadpage(divId, url) {
$('#' + divId).load(url);
return false;
}
.load() isn't supported by all browsers though. If you want to do this without .load() then you can check out .get(). For more info on .load(), take a look at http://docs.jquery.com/Ajax/load
I'm assuming it would go something like this:
$(document).ready(function(){
$("a").click(function(){
$("body").load($(this).attr("href") + " body");
return false;
});
});
This would make all <a> tags on the page call a function that downloads a HTML document from the href attribute of the tag, strip out it's body tag, and replace the contents of the current page's body tag with the contents of the new body tag. This way, it's easier to work this with no JavaScript, as well as integrate it into an existing site.
To use it, you place this into a <script> tag in the head of your main page, or in an external JS file.
Please note, however, that this code only updates the contents of the <body> tag, the head (including the title tag) remains untouched. You may need to add extra code to update things like this.
Simple and Nice. Check this out:
Bjax
Usage:
<script src="bjax.min.js" type="text/javascript"></script>
<link href="bjax.min.css" rel="stylesheet" type="text/css" />
Finally, include this in the HEAD of your html:
$('a').bjax();
For more settings, checkout demo here:
Bjax Demo

How can I implement "Generating... please wait" info for a web app (with and without JavaScript)

How can I implement showing "Generating data... please wait" information to a web browser from a web application (if data is not cached it can take some time to generate response), with and without JavaScript (AJAX)?
I am interested both in solution using AJAX (where I can replace loading message using JavaScript), and in solution using only server process, without JavaScript (if possible).
I'd like to replace loading message with response as soon as it is available.
Here's what I would do in implementing this client side.
This would be quite easy to accomplish using an Ajax call. Set a div on your page to show the "Generating... please wait" message when you first make the Ajax call. (A simple unimaginative animated graphic would suffice to cue the user's expectation of a pending operation. Convention = understanding = good interface.) Then pass a function into the readystatechange handler that updates the div with the message/progress graphic once the Ajax request returns.
function ShowPendingOperation(){
var resultHolder = document.getElementById( 'statusDiv' );
resultHolder.innerHTML = "Your data is loading... <img src='yourProgressAnim.gif'>";
var request = GXmlHttp.create();
request.open("post", "/yourScript", true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
request.onreadystatechange = function() {
if (request.readyState == 4) {
resultHolder.innerHTML = "operation complete";
resultHolder.innerHTML += "result1";
resultHolder.innerHTML += "result2";
resultHolder.innerHTML += "etc";
}
}
request.send( 'field1=data1&field2=data2' );
}
Note the snippet above is drawn from sample code written for a Google Map site, presumably your line creating the XMLHttpRequest object will vary...
You would need to use JavaScript to accomplish this without reloading the page. Here's a sample of using jQuery to create this type of effect.
http://trevordavis.net/blog/tutorial/ajax-forms-with-jquery/
The only way you could do this from the server side would be to show the message on the page you're POSTing to and write to the screen using a buffered output before you do the actual processing.
Here's what I would do:
When you determine that you have to perform a long operation, start a thread and associate that thread with an ID of some sort. Do not re-use the IDs.
Return the user to a page that says "Generating".
If ajax, use ajax to periodically poll the server or to perform a request that will block until the operation completes. This request has the ID in it and that is how the server knows what message to return.
If no ajax, use a meta-refresh to periodically reload the page with the specified ID. Repeat until the transaction is done. Note: in this case you should put a message on the page indicating when the refresh will happen and include a link to reload the page for people whose browsers don't support (or ignore) meta refresh.
JqueryUI's Tabs plugin has this built in, you could easily tie into their plugin to do what you want without having to write it yourself.
Without script: You could redirect to an intermediate web page with a "please wait" message that redirects to the result page when the process is complete.
With script: Your page could have a hidden div that shows up with a "please wait" message. That div could also be as big as your page and transparent (with the message in a smaller div) so that your users cannot click on the page while the message is displayed.
One of the trick I have found is to use <meta http-equiv="refresh" content="0" /> to redirect to ready view... but not closing html tag and not closing connection till the final response is ready:
print <<'EOF';
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="refresh" content="0"/>
<title>$title</title>
</head>
<body>
EOF
print "Generating...";
while (!is_ready()) {
print ".";
wait();
}
print <<EOF;
</body>
</html>
EOF
Is that something that has the chance of working, or does it work only by accident?

Resources