I am trying to to call a Java class when a button gets clicked from JSP. inside my JSP file I have the following:
<%
Object name = session.getAttribute("name");
Object ext = session.getAttribute("ext");
DBOps ops = new DBOps();
ReturnGetDisplayInfo GDI = ops.getDisplayInfo(ext);
%>
I have a method in DBOps that will delete a certain field so I added a button to teh table that displays the information and now I am trying to call the delete method when the button is clicked. so I tried doing the following but it did not work.
<td><button onclick=<% ops.delete(ext); %>>Delete</button></td>
I was looking at some examples that utilize javascript but it uses defiend functions in teh script rather than calling the Java class.
Thanks in advance
You can't do that directly. You need a roundtrip to the server.
The best option for that is AJAX:
make a servlet that handles performs the delete request when a certain url is invoked
use jQuery (or native XmlHttpRequest) to invoke that url
(DWR - direct web remoting is also an option, which is implemented using AJAX)
One example of my code, in javascript and ajax, if it can help you:
On my jsp i have a onClick"changeTimeZone(org)"
Javascript:
function changeTimeZone(org)
{
//Prepare a new ajaxRequest.
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function()
{
//state 4 is response ready.
//Status 200 is page found.
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
//fill the timezone field with the reponse of my servlet.
document.getElementById('timeZoneText').value = xmlhttp.responseText;
}
};
//send an ajax request.
//Go to my servlet
xmlhttp.open('GET','mainServlet?command=ajax.ChangeTimeZone&Org=' + org.value, true);
xmlhttp.send();
}
Related
I'm trying to call a function that returns me a json object from a servlet through a link.
My HTML link, call fTest function:
<td>ver</td>
My controller:
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {$scope.descargas = response.descargas;});
$window.alert(JSON.stringify($scope.descargas));
};
});
when I press for the first time the link appears "undefined" in the alert
but when I press a second time if I can see the json object that returns in the alert
What may be happening when I press first the link? please help
thanks
The problem here is your are alerting $scope.descargas outside of the success callback therefore it truly is not defined yet try modifying it like this.
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga){
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
$window.alert(JSON.stringify($scope.descargas));
});
};
});
Since every server side request using $http in Angular is an AJAX i.e. an asynchronous call to server, you are assuming that your alert method will be called after the success response execution complete. But this is wrong.
This is where the concept of promises comes in Angular.
app.controller('minaplantaCtrl', function($scope, $http, $window) {
$scope.fTest = function(idDescarga) {
console.log("1");
$http.get("http://localhost:8080/BD_INTEGRADA/UnionMinaPlanta?idDescarga="+idDescarga)
.success(function (response) {
$scope.descargas = response.descargas;
console.log("2");
});
console.log("3");
$window.alert(JSON.stringify($scope.descargas));
};
});
So when you execute this code with a delay at server side, you will see the order of console log as: 1, 3 and 2.
So, your success function is executed when the response received from the server. So for the first time, the value in descargas variable is null but get's stored using first server response and next time, value from previous call is being displayed.
I'm making an app with GoogleMap inside DJ Native webBrowser component. I load page as a string using webBrowser.setHTMLContent(String). HTML file contains JavaScript which add markers to map.
I made simple html file with google-maps-api functions.
It works perfect on Chrome as well as Firefox. But not in webBrowser (djnative).
I discovered that script without new marker statement(google.maps.Marker) works OK.
Have anyone got any idea what's wrong?
Is there any way to show console log from webBrowser (like ctrl+shift+J in Chrome)
This is script code:
<script type="text/javascript" src=https://maps.googleapis.com/maps/api/js?key=[MY_KEY]&sensor=false">
</script>
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.236302, 21.007636),
zoom: 10
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var t = [];
var x = [];
var y = [];
var h = [];
t.push('Location Name 1');
x.push(52.232097);
y.push(20.927985);
h.push('<p><strong>Location Name 1</strong><br/>Address 1</p>');
t.push('Location Name 2');
x.push(52.245097);
y.push(20.945985);
h.push('<p><strong>Location Name 2</strong><br/>Address 2</p>');
/*this is error making code*/
var i = 0;
for ( item in t ) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(x[i], y[i]),
map: map,
title: t[i],
});
i++;
} /*this is end of error making code*/
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
1.Dj is using ie as default. did you try opening the html with ie?
2.In dj, you can not always setting the content and expect it run. for example, the tinymce editor, does not run if you set the editor.html (html containint tinymce) directly. That is why the author of dj made internal webserver for editors. You have to call it through an address (for editor ck and tinymce, dj calls localhost, http://127.0.0.1/tinymce/.. but the structure is too complex to be detailed here. you may try for testing purpose, putting your html to a simple web page (tomcat) and call it through loadURL (instead of setContent)
My task is using hidden signed applet which support cryptography functions. Applet has to be loaded dynamically.
I try to use this example: (no links, just open first google search result from Oracle website) "invoking Applet Methods From JavaScript". The problem is when the applet is loaded and deployed with "deployJava.js" ZK window is disappearing.
My code is:
function loadScript(url, callback)
{
// Adding the script tag to the head as suggested before
var head = document.getElementsByTagName('head')[0];
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = url;
// Then bind the event to the callback function.
// There are several events for cross browser compatibility.
script.onreadystatechange = callback;
script.onload = callback;
// Fire the loading
head.appendChild(script);
callback();
}
function startApplet() {
var invokeApplet = function () {
var attributes = { id:'cryptoApplet', code:'CryptoApplet', width:1, height:1} ;
var parameters = { jar: 'clientcrypto.jar'} ;
deployJava.runApplet(attributes, parameters, '1.7');
};
loadScript("/js/deployJava.js", invokeApplet);
}
This problem happens because deployJava.js use "document.write(applet tag)" to add an applet.
I add div component to the page which has width="1", height="1", and rewrite deployJava.js to append applet in that div. And it's worked.
I am making ajax call to a java method for every 30 seconds.
I am setting few request parameters in the java method.
How can I get them from ajax response.
<script LANGUAGE="JavaScript1.2">
var tId = window.setTimeout(function () {
location.reload(true);
alert('<s:property value="#disableReload" />');
if('<s:property value="#disableReload" />' == "true"){
alert("clearing");
}else{
var url = 'moveETHAction_fetchExecutorData.action';
var form = document.getElementById('moveForm');
var params = Form.serialize(form) + '&ms=' + new Date().getTime();
form.action = "fetchExecutorData";
var myAjax = new Ajax.Request(url, {method: 'post', parameters: params, onComplete: showResponseAction} );
}
}, 30 * 1000);
function showResponseAction(originalRequest){
alert(originalRequest.responseText);
alert('<s:property value="#request[\'DISABLE_FLOW'\]" />');
document.getElementById('actionChange').innerHTML = originalRequest.responseText;
}
</script>
In Java method I am setting this parameter
request.setAttribute(GenericConstants.DISABLE_FLOW, false);
But I am not getting the updated value from the ajax
Any changes to the HttpServletRequest on the server side will not be visible on the client side. Moreover setAttribute method will not affect the incoming HTTP request string. It's additional store within HttpServletRequest to pass-around information on the server-side.
You need to add the information to the existing response, in a structured away (JSON is preferable for your client to convert into a javascript object right away and access the individual values within response). Hope this helps.
I am an Ajax fresher
Ajax
function ajaxFunction() {
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","Namelist",true);
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("txtname=" + txtname.value);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
jsp
<form name="fname" action="Namellist" method="post">
Select Category :
<select name="txtname" id="txtname">
<option value="Hindu">Hindu</option>
<option value="Muslim">Muslim</option>
<option value="Christian">Christian</option>
</select>
<input type="button" value="Show" id="sh" onclick="ajaxFunction();">
<div id="message">here i want to display name</div><div id="message1">here i want to display meaning</div>
</form>
servlet
String ct=null;
ct=request.getParameter("txtname");
Connection con=null;
ResultSet rs=null;
Statement st=null;
try{
con=Dbconnection.getConnection();
PreparedStatement ps=con.prepareStatement("select name meaning from (select * from namelist order by dbms_random.value)where rownum<=20 and category='+ct+'" );
rs=ps.executeQuery();
out.println("name" + rs);
**Here I have confusion,**
}
catch(Exception e)
{
System.out.println(e);
}
How can i diaplay servlet value to jsp.
Please help me? or please provide some good tutorial links.
You have to make below changes :-
In Servlet :-
Set the response content type as:- response.setContentType("text/xml"); in top section of the servlet. By setting this we can send the response in XML format and while retrieving it on JSP we will get it based on tag name of the XML.
Do whatever operation you want in servlet...
Save the value for ex-
String uname=";
uname="hello"; //some operation
//create one XML string
String sendThis="<?xml version='1.0'?>"
+"<Maintag>"
+"<Subtag>"
+"<unameVal>"+uname+"</unameVal>"
+"</Subtag>"
+"</Maintag>"
out.print(sendThis);
Now we'll go to JSP page where we've to display data.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
if(xmlhttp) {
xmlhttp.open("GET","NameList",true); //NameList will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
getVal();
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
function getVal()
{
var xmlResp=xmlhttp.responseText;
try{
if(xmlResp.search("Maintag")>0 )
{
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Subtag");
var xx=x[0].getElementsByTagName("unameVal");
var recievedUname=xx[0].firstChild.nodeValue;
document.getElementById("message").innerText=recievedUname;//here
}
}catch(err2){
alert("Error in getting data"+err2);
}
}
And here you are done. :)
1.In servlet code
PrintWriter output = response.getWriter();
String result = "value";
writer.write(result);
writer.close()
2. Why you don't use jquery ?
You can replace your code on -
$.post('url', function(data) {
$('#message1').html(data);
});
query post example
Probably off the hook but might be useful, rather than putting up all the javascript for Ajax call use some javascript library preferably jQuery for making the Ajax call.
Any javascript library you use will help you make the code compact and concise and will also help you maintain cross browser compatibility.
If you planning to write all the XHTTP code yourself, you might end up spending a lot of time for fixing cross browser issues and your code will have a lots of hacks rather than the actual business logic.
Also, using library like jQuery will also achieve the same stuff with less number of lines of code.
Hope that helps.