Is it possible to invoke a javaScript server side? - java

greetings all
i was wondering if it's possible to send some javaScript code in the response of a controller
meaning that i want to invoke a javaScript but not from the jsp (from server side)
something like:
var d = new Date();
var gmtHours = -d.getTimezoneOffset()/60;
var tz=gmtHours;
window.location="page?tz="+tz;
what do you think guys ?

There are two parts to the answer:
Executing JavaScript when the answer comes back from the server. To do that you can wrtite a Javascript in html, something like
<script>
alert("This code just executed");
</script>
usually people have something like
<script>
function init() {
document.getElementsByTagName('input')[0].focus();"
}
window.onload = init;
</script>
It will execute your function when windows loads.
It looks like you want to know the timezone for the user you are displaying results to. As mentioned, HTTP headers don't have this information, so you need to submit it or store as user preference.
If you don't want to store it, you either need to add it to every submit or URL. This way you will always have timezone on server side and you don't need to do 2 round trips.
The workflow might look like this:
1. User submits form or clicks a link -> 2. you form the results on server side -> 3. display results on client side.
Looks like you want to show some dates/times specific to timezone. If you send data to the client using ajax, you can then get it in javascript before step 3 and change it according to your preferences.
If you want to do all the formatting on server side you need to submit the timezone with the original request in step 1.
You can add 2 more steps 1.2 submit timezone request as a response to user action. 1.3 Re-submit the request with timezone info using javascript. This is not optimal, but could work.

I am still not very clear about the question. But it you are asking to invoke a javavscript when a response comes back from server than you can use AJAX and do your processing in the callback.
If you want to access the timezone than another way to send it as part of the parameter right in the beginning as a request parameter itself.

Related

Servlet with no answer

Is it possible to create a servlet that let's the browser of the client stay in that particular page, while at the same time changing a value of a session wide variable?
Basically I have a button on my webpage, which is encapsulated in an form that calls an servlet on submit. On that servlet I now want to increase a counter for that session by 1, but I don't want the page of the client to change, in case the user wants to press the button several times.
How can I program the servlet to not send back a response to the user, or if that's not possible, how do I sent a response that basically says: Don't do anything, stay where you are.
I tried simply not sending the response with .forward(), but the browser is then stuck on a blank page. I also tried .setContentType(null), but still nothing. Is this even doable?
Do an AJAX call to that servlet in client's browser using XMLHttpResponse object like var xhr = new XMLHttpResponse()
just google about AJAX request

Calling a java function with parameter within javascript function

is it possible to call java method within a javascript function? Let me explain my problem:
I am working with JSP (have to) and I have a JavaScript form validator which is checking whether a entered value is allowed. It depends on whether there already is such an entry in my MySQL DB. The Script looks like the following:
<script type="text/javascript">
<% DbConnection db = new DbConnection(); %>
function validateForm()
{
var x=document.forms["form"]["name"].value;
if (<%= db.validateName("%> x <%=") %>)
{
alert("Themenname bereits vergeben.");
return false;
}
}
</script>
So what I have to do is passing the entered value (javascript parameter) to my java method (db.validateName) in order to receive a boolean value.
Any idea how to solve this? Java runs server-side whereas JS runs on the client-side, right? Unfortunately I have no clue on how else I could validate from mySQL db.
Thanks in advance! :)
You need send to the server your validation, with AJAX, you can use a Servlet or another JSP validation that receives the validation input and response with validation result/message to the client.
render your html -> fire the event to validate -> send to the servlet/jsp in to server side -> validate into server -> response to the cliente -> in the client receive the server response -> in the client side render the validation menssage -> process form
You have to use AJAX.
You can have a look at DWR also if you want, here is the link http://directwebremoting.org/dwr/index.html

Establish Connection First, Redirect User Second

I have an idea to make something pretty sweet but I'm not sure if it's possible. Here is an example of a very basic ajax function that I might use to establish a connection a server...
function getFakePage(userId)
{
var ajaxObject, path, params;
ajaxObject = getAjaxObject();
params = "?userId=" + userId
path = getInternalPath() + "someServlet" + params;
ajaxObject.open("GET", path, true);
ajaxObject.send();
// On ready state change stuff here
}
So let's say I have a URL like this...
https://localhost:8443/Instride/user/1/admin
And I wanted to use javascript to redirect the user to this this URL. Normally I would just do this...
window.location = "https://localhost:8443/Instride/user/1/admin";
But my idea is to create a javascript (no js frameworks please) function that could combine the ajax code with the window.location code. Basically what I would like to accomplish is to create a connection with the server via ajax, send a servlet on that server the url I would like the user to be redirected to, and then redirect the user to that URL. So that for however long it takes the user to connect to my server from wherever they are in the world they see a loading icon instead of a blank white page.
So to clarify exactly what I am trying to accomplish; I do not want to put window.location within the success of my ajax function (because that would be encompass two round trips), and I do not want to return a huge chunk of HTML for the requested resource and add it to the page. I want to establish a connection to the server with ajax, send a servlet the URL the user wants to go to, and then somehow override the ajax function to redirect that user. Is this possible?
And I know some of you might think this is stupid but it's not when you're talking about overseas users with slow dial up connections staring at white pages. If it's possible, I'd love to hear some insight. Thank you very much!
First, let me say that the best solution is finding what is causing the slowness and fixing it.
Now as to your question, yes you could do it. You could even shoehorn it onto an existing application. But it wouldn't be pretty. And it comes with it's own set of problems. But here are the steps:
Browser calls ajax cache service requesting "somepage.html"
Browser loads loading icon
Server creates somepage.html and caches it in a temporary cache, (ehcache or other library would be good, probably with file backing for the cache depending on size)
Server responds to ajax request with ID for cached page
Browser now redirects to "somepage.html?cacheId={cacheId}" where the id is from the ajax call.
Server uses a filter to see if any cache can be served up for the page instead of the actual page, thus speeding up the request.
Having said that, it would be better to just have the new page load quickly with a loading icon while it did any of the heavy lifting through ajax.
You can't do an AJAX request and a location change in one. If you want to do only one request you have to choose one of those methods. ie. return some data and replace content on your current page, or load a completely new page.
It doesn't make any sense to want to want to do both. What you could want is stateful URLs; where your URL matches the content displayed, even if that content comes from an AJAX request. In that case an easy solution is the use the # part of the URL which you can change freely (window.location.hash). Some modern browsers support changing the whole URL without causing the page to reload. I've used # with great success myself.

How to get local date-time and not server date-time

I am making a Java web application in whcih customers in different countries are required to upload file through a jsp page.I have to deploy this application in Weblogic server.
Now what i want is their local date-time.I dont want server date-time.
What code should I write in my java application to get their local date and time.
It's tough to get time of user/client unless you pass it explicitly in the post/Ajax call.
Capture time in Javascript and then send it to server in http request.
URL : http://www.w3schools.com/jsref/jsref_obj_date.asp
You should have a look at this question: Determining a web user's time zone. Please see the answer of "JD Isaacks" with a lot of upvotes.
Than you can pass the timezone "offset" to your Java application through an ajax call and use it to calculate the users local date and time.
The only way to get the clients timestamp is to retrieve it on the client and send it to the server.
Using JavaScript() use Date() function and you can send it to server using ajax. You can call this javascript and ajax function right during bodyLoad().
Use following JQuery ajax call function.
$.ajax({
type: "POST",
url: "ServletTest",
data: "clientdate=" + new Date()
});
Try:
<script>
var d = new Date();
alert(d);
</script>

Applet web app interaction

I have an applet that calls a URL, on a user action, and passes some parameters. These parameters are executed on a ROR server and then I update a partial, which is on the applet's page, based on the result. However, the partial is not updating.
The console says that the partial is rendered but it is not. Is it because I am calling the URL from the applet and the server is unaware that the applet is in the current session, hence it does not know which session partial to render?
Here is the code of the controller:
def add_point
#comments = Comment.find(:all)
render :update do |page|
page[:comment_text].value = ""
page.replace_html :comments_partial, :partial => 'comments', :collections=>#comments
end
end
EDIT: I use Apache commons http wrapper to send the request:
PostMethod post = new PostMethod("http://localhost:3001/vizs/add_point");
post.addParameter("upload[test]", dataImg);
post.addParameter("upload[user_id]", new Integer(user_id).toString());
post.addParameter("upload[viz_id]", new Integer(viz_id).toString());
I think I need to set additional request variables but I am unsure what to set....
Any suggestion on how to solve this?
Thanks,
Slotishtype
rails is not aware about the applet, and does not know how to work with it, you need to send xml or json or even html:
def add_point
#comments = Comment.find(:all)
render :partial => 'comments', :collections=>#comments, :layout => nil
end
parse it in applet and fill appropriate fields by yourself.

Categories