struts2 ajax redirect - ajax

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).

Related

refresh <head> container of the website using 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
});

Redirect and keep Referral Url

I have a page which I redirect from it to another page (let's call it "middle page") with parameters in the query string. and I want to redirect from the middle page to some other page in another domain without losing the referral url (the query string of the middle page). my project is MVC C#.
I've tried:
- redirecting in the server side -> didn't work since the query string of the middle page didn't have a chance to change in the client side.
- redirecting in the client side through java script: location.replace/ location.href -> didn't keep the referral url.
- redirecting in the client side with Meta tag refresh -> didn't work.
I did see that if i place a link () in the middle page, clicking it would keep the referral url. so my last resolution was placing a javascript that automatically clicks on the link on document load-> it didn't work as well.
anyone has a solution for this?
I've solved it by using a timeout before I auto-click my link.
however I don't like this solution. does anyone have a better solution?
Try to submit a form using javascript: (Edited version)
So, we have a file "first.html" which calls "middle.html" with parameters:
<html>
<body>
<script>
document.location.href="middle.html?a=1&b=2";
</script>
</body>
</html>
Now "middle.html" makes form-submit to another domain:
<html>
<body>
<script>
var myForm = document.createElement("form");
myForm.method = "GET";
myForm.action = "http://google.com";
document.body.appendChild(myForm);
myForm.submit();
</script>
</body>
</html>
I checked it in FF with Firebug where under GET-request i can see HttpHeader "Referer" which equals to "middle.html?a=1&b=2"

Why does form validation not work in MVC3 partial views?

Anybody? There is another question regarding this but the only answers were to code up some javascript validation, which also refuses to work on my partial view ("$ is not defined").
Anyway, I don't want to use javascript I just want simple validation for required fields that cannot be left blank, number fields that require ints, etc.
Can anyone shed some light on validation and partial views?
I suspect that you are loading those partial views using AJAX. If this is the case you will need to manually invoke the $.validator.unobtrusive.parse method once you inject the new contents of the partial into the DOM as explained in this article.
Brad Wilson also discussed this in his blog post:
The unobtrusive client validation script automatically parses the
initial set of HTML for validation rules when the page has finished
loading. If your page dynamically adds new HTML content (perhaps
throught Ajax or through client-side application code), you may wish
to parse that new HTML for client validation on the new HTML elements.
To parse new HTML, you can call the
jQuery.validator.unobtrusive.parse() method, passing it a selector for
the HTML that you would like to be parsed. You can also call the
jQuery.validator.unobtrusive.parseElement() function to parse a single
HTML element.
As far as the $ is not defined error you should make sure that you have included the proper scripts:
<script src="#Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
Also make sure you are not referencing any of the Microsoft*.js scripts. They are obsolete and should no longer be used in ASP.NET MVC 3.
Of course that's only a supposition, you haven't shown any code so we cannot know what you are doing.
I'm having the same problem and i found that it's not possible to call $.validator.unobtrusive.parse() on the same form twice.
When loading the form initially from the server the form is parsed automatically by the unobtrusive library. When you add an input element dynamically to the form and call $.validator.unobtrusive.parse() again, it won't work. The same goes for parseElement().
So before you call $.validator.unobtrusive.parse, remove the original validator and unobtrusive validation from the form like so:
success: function (html) {
$("#div-id").append(html);
var form = $("#div-id").closest("form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse($("#editorRows"));
}

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?

What are the differences between using an iframe and ajax to include the contents of an external page?

I have been reading up on this, and it seems that if you use ajax you can only bring in content that resides on the same domain whereas with an iframe you can bring in content from any domain. Is that the case? What other differences are there?
Bear in mind they're two completely separate technologies.
A (i)frame really loads a complete HTML page in area into the browser. Whether the page is on the same or another domain, for pure viewing, doesn't matter.
Ajax only describes a system to facilitate JavaScript to talk with (and with current security restriction across browser, only with) the server from which you document within which you generated the JavaScript call from.
The (i)frame technology loads and renders a complete HTML page from any URL given. Certain security restrictions accessing other documents from other domains with JavaScript still apply.
With Ajax, it's only meant to use purely JavaScript to talk to the originating server (send some data) and usually get some data back. In JavaScript. What this data is and what you do with it, is up to you. Whether you insert it into the DOM (Document Object Model), exchange parts or load a new page is up to you.
To a certain degree you have all freedom you want. You can have an (i)frame on a page, still make a Ajax call and decide to load another URL into the (i)frame. Or use the Ajax return value to generate new HTML dynamically inside the (i)frame. Or outside, in another document.
The security restrictions applying in this case is called "same origin policy".
Quite simply, an iframe is like a regular frame, but it doesn't split the browser window up into sections, it sits right inside a page and is affected by the scrollbar.
Ajax, on the other hand, uses javascript to do partial loads of a page, allowing small amounts of data to be loaded from the server without needing to do a complete postback. For example, Youtube uses Ajax when you post comments, vote, queue videos to play, etc. They do this so that your video isn't interrupted and restarted by a complete page postback.
Besides these differences mentioned by others, there are others as well.
iframe loads an entire html/php page, whether it is from the own server or other external server. Usually, it has a fresh <html>, <head> and <body> tag as well. Ajax only loads part of the html/php page.
Besides, Ajax pulls the CSS (and maybe, even javascript codes) from the parent file, but in case of Iframe, it cannot pull the same.
E.g this is the master file coding.
<!doctype html>
<html>
<head>
<style>
.gappu {background-color:black;color:red;}
</style>
<meta charset="utf-8">
<script src="../AllJqueries/jquery-1.11.3.min.js"></script> <!-- Use your own jQuery file -->
<script>
<!--
$(document).ready(function(){
$.ajax({url:"slave1.php?bare=true", success:function(data){
$(".myDomain").html(data);
}});
}); /* End of Main Jquery */
//-->
</script>
<title>Ajax vs Iframe</title>
</head>
<body>
<div class="myDomain"></div>
<div>Iframe below</div>
<iframe width="100%" height="500px" src="slave1.php"></iframe>
</body>
</html>
Now, we also have another file, named as slave1.php
<?php
if(isset($_GET['bare'])) $bare = $_GET['bare'];
else $bare = false;
if(!$bare):
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<style>
.gappu {background-color:blue;color:yellow;}
</style>
<!-- You can remove the above style later, and see the difference. The parent style will not apply for iframe -->
<title>Inside the Iframe</title>
</head>
<body>
<?php endif; ?>
<div class="gappu">Hi, welcome to this demo</div>
<?php if(!$bare): ?>
</body>
</html>
<?php endif;
In case of Ajax call, the line Hi, welcome to this demo will be in black background and red color, since it is borrowing the css from the parent. But in iframe, it will be in blue background and white color, which is defined in slave1.php. You can remove the style from slave1.php, and you will find plain text printed in iframe format.
Hope this helps. Cheers.
Vijay Srinivas

Resources