Calling Java inside JavaScript Function - javascript

Please tell me if we can call java inside javascript function ?
<HTML><HEAD></HEAD><BODY>
<SCRIPT>
function getScreenDimension() {
<% System.out.println("Hiiiiiiiii"); %>
}
</SCRIPT>
<FORM>
<INPUT type="button" value="call Java method direct" onClick = "getScreenDimension()">
</FORM>
</BODY></HTML>

While the answer of "No" is technically correct based on the phrasing of the question. You may want to read up on AJAX. It is a way for javascript to make a request to your backend code (in this case Java).
Javascript is client side, meaning it is run by the user's browser. Java is running on your server. In order for the client side javascript to interact with the backend Java, you need to make a request to the server.

My question to you would be, "What are you trying to do, and what do you expect to see?".
You have to realize that there are two different execution contexts. The first is the JSP itself whose code is executed by the JVM on the server-side, and the second is the Javascript that is executed by the browser. So when the code goes to the browser, you'll see: So the System.out.println will cause Hiiiiiiiii to be printed to the server logs, but you won't see anything on the browser. In fact, the Javascript code on the browser will look like this:
function getScreenDimension() {
}
Which is not valid Javascript code. The code in the JSP is run before the Javascript gets run on the browser. So to "run" Java code, you need to make a request to your server either by posting the form or with an AJAX call. This will cause Java code in the appropriate servlet or controller, to run.
UPDATE
After glancing at your code, it appears that you want to call a Java method directly. This is not possible with your current code. You might want to read up on AJAX. This will point you in the right direction.

JSP runs on the server. It generates a document which the server sends to the browser. That is the end of the involvement of JSP in the process. The browser then parses the document and runs any JS.
You can include JSP in a script element, it just has to output valid JavaScript.
You cannot have JSP that runs in response to JavaScript, other then when JavaScript causes the browser to issue a new HTTP request (either setting location.href, submitting a form, adding an image, or using Ajax, etc)

I think you have lack of understanding of what is going on here. Anything in middle of <% %> is executed when the page is first requested. Anything in javascript is executed when the browser calls it. What you have will never happen and there is no way to make it happen. However, you can use AJAX to do something like this but that's a different question.

Yes, you can. Use JSP expressions <%= %>. Example:
<aui:script use="aui-datepicker">
AUI().use('aui-datepicker', function(A) {
new A.DatePickerSelect({
calendar : {
dates : [ '<%="1/1/1970" %>' ],
}
}).render('#myDatePicker');
});
</aui:script>

Yes, you can call Java from Javascript, both if you mean the Java-VM on the server and on the client; i assume you mean the client (the VM in the browser); take a look here:
http://www.apl.jhu.edu/~hall/java/Java-from-JavaScript.html

You can. In JSF you can use PrimeFaces' component p:remoteCommand, which would contain action method. Call that remoteCommand by its name from JS and the java method will get executed.
JSF Page
<p:remoteCommand name='rmt' action="#{bean.doWork()}"/>
In JavaScript
function callJava {rmt();}

Use JSP code
<%
// Respond to the application with 1) result, 2) update, and 3) updateid values
String result = "blablabla";
out.print(result);
%>

Related

calling PhP function in JavaScript returns white screen

Before anyone complains: i know that javascript is clientside and php is serverside.
I need to call a php-function within my javascript (both in the same file). i used
document.write("<?php add(); ?>");
which calls the function from php like it should. the main problem is that the page turns white (like when i call echo "";), which should not happen. i tested with an completly empty test();, ending up in the same problem.
to answer the question why i want to call the function: i need to update a sql table on pressing a key. as far as i know its impossible to make a keylistener in php and too unsafe to use sql in javascript.
greetings and thx for help
When you use document.write at any other moment than during page load, it will wipe out your document and replace it with whatever you pass as argument. From your question it seems you run this code in an event handler, like for the keypressed event. In this case, it is expected behaviour of document.write that your page turns white. Don't use it there.
What you need to do is identify where in your document you want to insert content, more precisely, at which element, and provide content to it. You can use several methods for this, like .innerHTML, but not document.write.
Secondly, you should understand that when you pass an argument that has php generated values in it, that these arguments are calculated at the moment php generates the page, and not when the corresponding javascript executes. At that latter moment no call to php takes place, as php already did it's job during the generation of the page.
If you want to execute a php function at the moment of an event in the browser, you should issue an http request to the server. This can be done by submitting a form, by navigating to a different url, or by issuing an ajax call. In these cases the server receives a request, and php can be executed, which will again generated content and send it back to the browser.
You can find example ajax code on the internet, for example here.

Get return value from JS code to C#

I want to get the answer of a window.prompt() alert box through the C# Code Behind file. It's just a one-liner of JavaScript code, so I thought I could even execute it from the Code Behind file. It doesn't really matter to me whether it's a <script> tag in the .aspx file or executed through the .aspx.cs file.
I thought of having the script executed (called from the C# part) and then having the return value assigned to a certain not visible field, but is there any better way to do it?
The obvious way would probably go something like this:
.aspx file:
<script>
function foo() {
document.getElementById('MyFieldID').value = window.prompt('Answer this question:', '');
}
</script>
.aspx.cs file:
////////////////////////////////////////////////
//MyFieldID.Text now contains whatever I want//
//////////////////////////////////////////////
What do you say? Is there any better way?
Better way is always opinion based. What I'd say is you have a few options, all depend on what you're doing. HTTP and ASP.NET provide us a few means of sending data to the server, there are 3 main ones before HTML5:
Query string
Form values
AJAX calls
If you're redirecting the user to a new page after they answer the prompt, you can just send them to yournewurl.aspx?promptAnswer=*whatever*
If you're doing a postback, then you can use a form value (this looks like what you're doing in your example). You can put an <asp:HiddenField> on the page and populate it from JavaScript before submitting the form.
If you need just the prompt response, but are not attempting to reload the page, you can make an AJAX call that sends the variable to the server (this still uses #1 or #2 to send the data, it just does it without reloading the page).
Which of those three options works best depends on your implementation. However, your solution should work just fine. However, since the control you'd likely be using to stuff the value into is a HiddenField it would be in MyFieldID.Value not MyFieldID.Text. The only other thing you have to deal with is if your MyFieldID is nested in some other controls (like a ContentPlaceHolder) such that the ClientID has naming containers pretended to it so it's really something like ContentPlanceHolder1_MyFieldID when accessed from JavaScript.

Ruby code in a JavaScript function

I'm new in the world of JavaScript, jQuery, and Ajax. I have a JavaScript function where I want to use the value of a JavaScript variable inside of embedded Ruby code. For example, below I want to use the JS p variable as an argument to the Ruby call to #r.search():
$(function (){
$('#data-select').on('change',function (){
var p = document.getElementById('data-select').value;
alert(<% j #r.search(+ p +) %>);
});
});
I want to know if i can do this? And if i can what's the syntax?
First off, I'm assuming this is Ruby on Rails (which you tagged it as). When using ERB you are telling Rails to first evaluate the embedded Ruby code to dynamically insert data that is on the server-side, and then send the file to the client over the internet where their web browser then evaluates the JavaScript.
So if this is what's in your file, and you passed a #user variable with a name method that evaluates to "John Smith":
// test.js.erb
alert("Hello <%= #user.name %>");
When that file is rendered, your server will evaluate it to this:
// test.js
alert("Hello John Smith");
And then send that over the internet to the client. Only once the client's computer has received this file will the JavaScript be evaluated. They (and the JavaScript) will therefore never see the embedded Ruby code. Therefore what you're doing cannot be done the way you have it because the Ruby code is evaluated before the JavaScript can set the p variable.
If you want to get information that resides on the server after the client has received the file and is running the JavaScript, you can use something called Ajax, which uses JavaScript to send data asynchronously back to the server. Check out this Rails guide for more details on that.
You Can't do it, because while rendering the view all ERb will be converted to HTML or relevant, so you don't have access tp the Ruby objects after rendering the view.
You can also pass the dynamic values from javascript to certain rails methods
Refer: http://apidock.com/rails/ActionView/Helpers/PrototypeHelper/remote_function
But this rails method also will converted to ajax function after rendering.
The solution:
Try to send an ajax request and show the result in view.

How to prevent a Ruby method inside a jQuery onclick event from executing on page refresh

I have a Ruby method nested inside a jQuery onclick event and I want the method to execute when the div is clicked. This works; however, the method is also executing on page refresh. Why does it also execute on page refresh and is there any way to limit it to only onclick?
$(function() {
$('.myDiv').click(function(){
<% foo_bar %>
});
});
I don't see how foo_bar can be executed when you click on the div. Ruby is executed server side, jQuery is executed client side. You cannot execute ruby code from your client.
Your foo_bar is executed on refresh page because the server need to interpret it to give it's result into the <% %> tag. However, when you click on the div, nothing will happen because the jquery function will be empty (since you did not write <%= %>). Even if you wrote <%= %>, the jQuery would only execute the foo_bar result, not the function itself.
Maybe you could explain what you want to do in your foo_bar. If you want interact with the server, you will need something like Ajax.
Please review this blog entry I wrote. In short, the ruby code executes on the server, and the javascript, which runs on the client, sees nothing. To have javascript interact with ruby, you need to initiate a request back to the server via some kind of ajax request. Libraries like jquery help with this.

Is it possible to call javascript function to the pageload event in asp.net?

Suppose i have created one .js file name as: MyNoteBook.js. In this .js file i have written function as name count().
Now I am creating MyNoteBook.aspx page in asp.net. On the event of pageload of .aspx file, i want to call that count() function of that .js file. Is it is possible, If yes then please tell me.
If no, then how i can write count function in .aspx page?
To call a JS function on page load, make sure there is an onLoad attribute on the body tag that calls it:
<body onLoad="count();">
This all happens client side, as Javascript runs in the browser.
You can't call a client side function from server side code.
As for writing the function server side - without knowing what it does, no one can tell you how to convert it to server side code.
you could use ClientScriptManager.RegisterStartupScript
have a look at:
http://msdn.microsoft.com/en-us/library/z9h4dk8y(v=VS.90).aspx
One possibility is to use the javascript pageLoad function from the ASP.NET Ajax framework. You can find more information about the ajax client-side life-cycle events here.

Categories