How to call action with parameters of JSP Servlet from JavaScript? - java

function printthis()
{
var content_vlue = document.getElementById('print_content').innerHTML;
var target= 'printValue?value1='+content_vlue;
document.forms[0].action = target;
document.forms[0].submit();
}
<div id="print_content">hello i am good</div>
For frontend I am using JSP. While executing this code to get the value in servlet
String msg = request.getParameter("value1");
While executing this code the browser url changes to printValue?
But I am unable to get the value of value1
Please suggest me...

Seems you are missing value1='+content_vlue from the request
try this and see
var target= "'printValue?value1="+content_vlue+"'";

Create a hidden variable inside your form like this
<form ..>
....
<input type="hidden" id="value1" name="value1"/>
</form>
and modify javascript function to this .
function printthis()
{
var content_vlue = document.getElementById('print_content').innerHTML;
document.getElementById('value1').value = content_value;
var target= 'printValue';
document.forms[0].action = target;
document.forms[0].submit();
}
Hope this will work for you.

Related

How to return value from a jsp page

I have a jsp page which has java scriplets, and which is displaying the required output using out.println(obj), but I want to return this 'obj' so that these values can be used in another js file. How to return this from the jsp page?
So the js file is:
(function() {
document.addEventListener('DOMContentLoaded', function() {
var gridDiv = document.querySelector('#myGrid');
var gridOptions = {
columnDefs: [
{headerName: 'CLIENT_ACRONYM', field: 'CLIENT_ACRONYM'},
{headerName: 'ORDER_QTY', field: 'ORDER_QTY'},
]
};
new agGrid.Grid(gridDiv, gridOptions);
jsonLoad( function(data) {
gridOptions.api.setRowData(data);
});
});
})();
function jsonLoad(callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', '../output.json'); // by default async
xhr.responseType = 'json'; // in which format you expect the response to be
xhr.onload = function() {
if(this.status == 200) {// onload called even on 404 etc so check the status
callback(this.response);
}
};
xhr.onerror = function() {
console.log('loading data error');
};
xhr.send();
}
JSP file returning Jsonarray:
JSONArray jsonArray = new JSONArray(orderDetailsList1);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(jsonArray);
So, instead of output.json in the js file I need to pass the JSOn Object returned by the jsp file. How to do that?
Use this code in jsp file
<input type="hidden" value="<%out.println(obj);%>" id="objValue"/>
In js file you can get the value by its id as
var objValue = document.getElementById("objValue");
Basically scriplets in jsp is not good.
Store in session scope or request scope and use it,like session.setAttribute('obj','value') in servlet and value="${obj}" in jsp.
Put that value in <div id=""> or <p id=""> tag which has ID in jsp and get that value in any js using getElementByID.

Want to pass the java value into javascript function in jsp

I am trying to pass a string value to a JavaScript function by taking from request parameter in JSP, in my struts based project. here is the code:
<%
String timeVal = "Not found";
if(request.getAttribute("myDate")!=null){
timeVal= (String)request.getAttribute("myDate");
}
%>
and then pass it in function as parameter
<html:submit property = "save" styleClass = "button_c" onclick = "return SubmitPage('update', <%=timeVal %>)">Save</html:submit>
Where the JavaScript function is
function SubmitPage(action, aa)
{
alert("Date is ...." + aa);
}
But when i try to run this it gives me an error
HTTP Status 400 - Request[/AMResourceLibraryListAction] does not contain handler parameter named ref
With message on web page.
Request[/AMResourceLibraryListAction] does not contain handler parameter named ref
Thanks in advance.
EDIT Here is stack trace
[ERROR] DispatchAction - -Request[/AMResourceLibraryListAction] does not contain handler parameter named ref
it's work for me :
<html:submit property = "save" styleClass = "button_c" onclick = "return SubmitPage('<%=timeVal %>')">Save</html:submit>
('<%=timeVal %>') // between single Quotation
Rather using that i will advise you to use value like this in your JavaScript function
var tt = <%=(String)request.getAttribute("myDate")%>
alert(tt+ "Done this....");
Hope this will help you.
Use '<%=timeVal %>' instead of <%=timeVal %> in Javascript method:
<html:submit property = "save" styleClass = "button_c" onclick = "return SubmitPage('update', '<%=timeVal %>')">Save</html:submit>

Not able to retrieve value of parameters from JSP page

Suppose
home.jsp code contain a button like
<input name="R" onclick="del(<%=rs.getString("VDB")%>)" type="radio" value="<%=rs.getString("VDB")%>" />
//note: i am passing value of VDB in del()
it is calling javascript as :
<script type="text/javascript">
function del(delno)
{
var ff = document.vendorform;
var url = "delete.jsp?+vendor="+delno;
window.navigate("delete_vendor.jsp?+vendor="+delno);
//window.location.href="delete_vendor.jsp?+vendor="+delno;
//ff.method = "POST";
//ff.action ="delete_vendor.jsp?+vendor="+delno;
//ff.submit();
}//i have used 3 methods to redirect to delete.jsp
delete.jsp :
on this page i want to retrieve value of vendor i used :
String D1=request.getParameter("vendor");
But getting null value.
Any help
var url = "delete.jsp?+vendor="+delno;
you have inserted wrong string +vendor. it should be only vendor in url.
var url = "delete.jsp?vendor="+delno;
Remove the "+" before the word vendor. Change
var url = "delete.jsp?+vendor="+delno;
To
var url = "delete.jsp?vendor="+delno;

How to show value from database to jsp without refreshing the page using ajax

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.

java equivalent of swfobject

looking for a javascript class like swfobject to embed java and have a simple fallback if the user doesn't have java or refuses the security prompt.
thanks,
Josh
You could build one pretty easily.
Have something like a div set up like this:
<div id="java-applet">
Message to user saying that they need Java here
</div>
Then add Java Plugin Detection (builder) to your JavaScript. Then if that returns true, then do something like:
document.getElementById("java-applet").innerHTML = "<applet>stuff here</applet>";
appletobject may work, but I have not used it.
Just embed the applet like you normally do and insert the fallback inside or insert a javascript snippet to remove the object: Besides param, you can add other elements, e.g. paragraphs with text or javascript calling some function to replace the object.
<script type="text/javascript">
function replace_object(x) {
$(x)...
}
</script>
<object x="y" id="some_applet">
<param name="y" value="z">
<p>java not available. some alternative here. <!-- option 1 --></p>
<script type="text/javascript">
replace_object('some_applet'); // option 2
</script>
</object>
This helps!
I got a very strange problem while using applet to do batch file downloading from the server side.
The Ajax request seems conflict with applet request, the applet file downloading interrupted with some socket exception.
The applet works fine under JRE5.0, it might be caused by our recent upgrade to JRE6.0.
<div id="java-applet"></div>
<script>
var t;
function startApplet() {
var attributes = {codebase:'<%=request.getContextPath()%>',
code:'<%=appletClass%>',
archive:'applet/SignedApplet.jar',
width:0,
height:0} ;
var parameters = {para1:'value1',
para2:'value2',
java_arguments:'-Xms64m -Xmx512m'
} ;
var version = '1.6' ;
var buildAppletTag = function() {
var tag = '<applet';
for (var attribute in attributes){
tag += (' ' + attribute + '="' + attributes[attribute] + '"');
}
tag += ">";
for (var parameter in parameters){
tag += '<param name="' + parameter + '" value="' + parameters[parameter] + '"/>';
}
tag += '</applet>';
return tag;
};
document.getElementById("java-applet").innerHTML = buildAppletTag(attributes, parameters, version);
clearTimeout(t);
}
t = setTimeout("startApplet()", 1000); // delayed
</script>

Categories

Resources