Home Answers Viewqa JSP-Servlet calling servlet from JS and return response from servlet to JS

 
 


anky
calling servlet from JS and return response from servlet to JS
3 Answer(s)      a year and 3 months ago
Posted in : JSP-Servlet

hello all,

I am working on JSP-servlets n MVC.I am facing a problem.

on the web page when user clicks on a button i am calling a javascript function(eg myFunc) which inturn calls a servlet(myServlet).servlet performs some DB related task.now i want this servlet(myServlet) to return a url(eg. pages/file.jsp) to the function myFunc and the myFunc will load that file(url) on the same webpage using Ajax.

i tried following:

in servlet::

String url = "loadData.jsp";

response.setContentType("text/plain");

response.getWriter().write(url);

in js function::

document.forms[0].action = "LoginDetailsServlet";

document.forms[0].submit();

var url = xhr.responseText;

loadDoc(url); //ajax goes here

but this is not working :(

any suggestions how can i do this???

thanks in advance!!!

View Answers

February 23, 2012 at 3:59 PM


1)application.jsp:

<%@ page import="java.sql.*" %>
<html>
<head>
<script language="javascript">
function editRecord(id){
    var f=document.form;
    f.method="post";
    f.action='http://localhost:8080/examples/jsp/edit.jsp?id='+id;
    f.submit();
}
function deleteRecord(id){
    var f=document.form;
    f.method="post";
    f.action='http://localhost:8080/examples/DeleteServlet?id='+id;
    f.submit();
}
</script>
</head>
<body>

<br><br>
<form method="post" name="form">
<table border="1">
<tr><th>Name</th><th>Address</th><th>Contact No</th><th>Email</th></tr>
<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "test";
String driver = "com.mysql.jdbc.Driver";
String userName ="root";
String password="root";

int sumcount=0;
Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url+db,userName,password);
String query = "select * from employee";
st = con.createStatement();
ResultSet rs = st.executeQuery(query);
%>

<%
while(rs.next()){
%>
<tr><td><%=rs.getString(2)%></td>
<td><%=rs.getString(3)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
<td><input type="button" name="edit" value="Edit" style="background-color:#49743D;font-weight:bold;color:#ffffff;" onclick="editRecord(<%=rs.getString(1)%>);" ></td>
<td><input type="button" name="delete" value="Delete" style="background-color:#ff0000;font-weight:bold;color:#ffffff;" onclick="deleteRecord(<%=rs.getString(1)%>);" ></td>
</tr>
<%
}
%>
<%
}
catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>

2)edit.jsp:

<%@page language="java"%>
<%@page import="java.sql.*"%>
<form method="post" action="../UpdateServlet">
<table border="1">
<tr><th>Name</th><th>Address</th><th>Contact No</th><th>Email</th></tr>
<%
String id=request.getParameter("id");
int no=Integer.parseInt(id);
int sumcount=0;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
String query = "select * from employee where id='"+no+"'";
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next()){
%>
<tr>
<td><input type="text" name="name" value="<%=rs.getString("name")%>"></td>
<td><input type="text" name="address" value="<%=rs.getString("address")%>"></td>
<td><input type="text" name="contact" value="<%=rs.getInt("contactNo")%>"></td>
<td><input type="text" name="email" value="<%=rs.getString("email")%>"></td>
<td><input type="hidden" name="id" value="<%=rs.getString(1)%>"></td>
</tr>
<tr>
<td><input type="submit" name="Submit" value="Update" style="background-color:#49743D;font-weight:bold;color:#ffffff;"></td>
</tr>
<%
}
}
catch(Exception e){}
%>
</table>
</form>
</form>

February 23, 2012 at 3:59 PM


continue...

3)UpdateServlet.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class UpdateServlet extends HttpServlet { 
        public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
String id=request.getParameter("id");
int no=Integer.parseInt(id);
String name=request.getParameter("name");
String address=request.getParameter("address");
int contact=Integer.parseInt(request.getParameter("contact"));
String email=request.getParameter("email");
try{
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root");
Statement st=null;
st=conn.createStatement();
st.executeUpdate("update employee set name='"+name+"',address='"+address+"',contactNo="+contact+",email='"+email+"' where id='"+no+"'");
response.sendRedirect("/examples/jsp/application.jsp");
}
catch(Exception e){
out.println(e);
    }
  }
}

4)DeleteServlet.java:

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;

public class DeleteServlet extends HttpServlet { 
    public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
String id=request.getParameter("id");
int no=Integer.parseInt(id);
int sumcount=0;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st = conn.createStatement();
st.executeUpdate("DELETE FROM employee WHERE id = '"+no+"'");
response.sendRedirect("/examples/jsp/application.jsp");
}
catch(Exception e){}
    }
}

February 24, 2012 at 10:54 AM


hi.. thanks for ur reply!! nice example but where the AJAX is coming into picture??? in above case the page reloaded again but i dont want the full page to be loaded again.i want servlet to return a xml file and load it through ajax!!









Related Pages:
calling servlet from JS and return response from servlet to JS
calling servlet from JS and return response from servlet to JS  hello... task.now i want this servlet(myServlet) to return a url(eg. pages/file.jsp... page when user clicks on a button i am calling a javascript function(eg myFunc
Ajax+servlet+js
in 1st text box,after click on button i must get value from servlet in 2nd text...Ajax+servlet+js  1) new.jsp <%@ page language="java..., HttpServletResponse response) throws ServletException, IOException
js,,mysql - JSP-Servlet
js,,mysql  Hi, I want a jsp code for editing,deleting data retrieved from from the mysql database and displayed in a html page .Can anybody provide me a code for including edit and delete options with the following code
JS - JSP-Servlet
the records from the table and display it in tabular form
Ext Js form example.
framework and create web application Download latest version of Ext Js from the official...; In this simplified application and easy to learn Ext Js Tutorial I will show you how to develop a form in Ext Js framework. The Ext Js form will take
EXT JS
retrieved data from database and set the value for grid panel. i set a value.... how to set the value for the check box from mysql in extjs grid. below is my... AccountNumber,AccountNumber,Fullname,AccountType,MobileNumber,Email from details
Calling servlet from servlet .
Calling servlet from servlet .  How to call a servlet from another... ServletException, IOException { System.out.println("Calling another servlet by using...); System.out.println("Calling another servlet by using SendRedirect
EXT JS
EXT JS   i want to create a grid in extjs to display data from mysql and if i want to edit the data i must update through extjs only and must update in mysql database. please help me with sample code. thank you
calendar js
chosen from first calendar , the second calendar should be disabled till that date. for eg once i have chosen date 21-03-2012 from first calendar... should be disabled from being chosen.   Please visit the following link
EXT JS
EXT JS  Hi, how to redirect from one extjs page to jsp page. i have a grid in extjs and in that grid i have a check box and i set the unique value for each checkbox. when i choose a check box and click the edit button it should
calling servlet from jsp
calling servlet from jsp  how to call a servlet from jsp
How to change the value of a variable which is set in jsp (by jstl method) by calling the function from js?
) by calling the function from js?  How to change the value of a variable which is set in jsp (by jstl method) by calling the function from js? I set... the value of 'name1' as "Edit User" when calling the editUser function which
js - Java Server Faces Questions
) { document.location=URL; return false; } 2. Now... the above function from onClick attribute of the link like below, Click here
Calling a jsp page from Servlet
Calling a jsp page from Servlet  How can I do this? Suppose I have jsp page aaa.jsp. From aaa.jsp on form action I have made a call to a servlet xxx.java. In xxx.java I have written code to retrieve data from database through
calling servlet from jsp in netbeans ide
calling servlet from jsp in netbeans ide  I have tried to call servlet from jsp code in netbeans for checking the database values . but while running it showing the error that the resource not available. i dono wat mistake i did
Create a input button inside js function
Create a input button inside js function  I call my js function from HTML code from another file. Now I would like to create a input button on page... is the right way   I call my js function from HTML code from another file
Calling from JSP
Calling from JSP  how can we call a class file from JSP   Hi, Do you want to call a servlet or a Java Bean through JSP? Please clarify this. For more information, visit the following link: JSP Tutorials Thanks
Passing java variables from JSP to Servlet - return null values
Passing java variables from JSP to Servlet - return null values  I want to pass some variables from a JSP page to a servlet. These variables are from... from JSP to servlet gives null values. I got msg=null. Is there another way
calling java beans - JSP-Servlet
calling java beans  Sir, I want to know where to place the java... from jsp file.  Hi Friend, Java Bean is placed in classes\form... text="Hello World"; public String getText() { return text; } public Bean
Send a Response Status in servlet
example shows how a response has been send from the servlet. If the requested...; This section illustrates you how to send response status in servlet. All.... Constants value request and response are used to return status to browser
calling a session bean bean from servlet using netbeans - EJB
calling a session bean from servlet using netbeans  How to call a session bean from servlet using netbeans in Java
servlet session - JSP-Servlet
that called the servlet: like in JS we can call a previous page... response (as a general servlet response...servlet session  hi, im working on a real estate web site.....n
js - Java Beginners
conlabeng!") testresult=false } return (testresult) } function checkban(){ if (document.layers||document.all||document.getElementById) return checknumber() else return true } change the form tag
calling webservices that return complexTypes in android using ksoap2
calling webservices that return complexTypes in android using ksoap2   Here's my code for android application,to call aweb service method and return a complexType object from it. package com.example.gramaniladharidetails
Servlet Response Send Redirect - JSP-Servlet
Servlet Response Send Redirect  Hi, Thank you for your previous... from the visit table. Can you please show me how I can pass more than one column value to the next jsp? 2. I have a servlet that saves patient data from
write to file from servlet - JSP-Servlet
and POST methods. * @param request servlet request * @param response servlet response */ private String name=null; private String... method. * @param request servlet request * @param response servlet
calling one jsp from another jsp - JSP-Servlet
calling one jsp from another jsp  Hi All, In my web application... in two.jsp by using jsp declarative tag. Now from one.jsp file I want to call... start from where we call this two.jsp files method. i.e. in one.jsp file at line
calling java method from html form with out using javascript - JSP-Servlet
calling java method from html form with out using javascript  How can i call java method from a HTML form, java script should be disabled?  ... isNumberString(InString){ if(InString.length==0) return (false); var RefString
Lightbox JS
Lightbox JS/font>       Lightbox JS is a simple, unobtrusive script used to overlay images on the current page. It`s a snap to setup and works on all modern browsers. Read full
calling function - JSP-Servlet
calling function  Hai, How to call a java file in jsp file?  Hi friend, Step to be remember for solving the problem... class Extends{ public String show(){ return "Roseindia.net
xls to js using javascript
xls to js using javascript  ![how can we convert a xls file in js file using javascript][1
JSP:NEED RESPONSE ASAP PLEASE! - JSP-Servlet
JSP:NEED RESPONSE ASAP PLEASE!  Hi freind, If you could respond to my previous thread which hasn't been addressed for over a week, I'd really... have a javascript that captures data from a highlighted row in a table
Java from JSP - JSP-Servlet
Calling Java from JSP  Does anyone have an example of Calling Java from JSP
Sending form data from HTML page to SQLserver 2005 database by calling servlet code
Sending form data from HTML page to SQLserver 2005 database by calling servlet... from html page to database by calling servlet code from html page .   ...(); } catch(Exception e){ out.println(e); } } } 3)Do the servlet
Call servlet from javascript - JSP-Servlet
Call servlet from javascript  Hi in my application i have jsp that designs view, javascript for validation and servlet that perform business logic.../jqueryPostData.shtml Thanks    i am calling servlet in this manner var answer2
Calling Servlet to build a List of data from database and show this on the JSP page in table
Calling Servlet to build a List of data from database and show this on the JSP...;    In this example we are calling a servet to retrieve all the data from database and then add the data into list. The list
servlet
com.ilp.tsi.pm.services.StockService; /** * Servlet implementation class AddServlet1 */ //Servlet for Adding the stock public class AddStockServlet extends... response) throws ServletException, IOException { } protected void
Response Filter Servlet Example
Response Filter Servlet Example       This Example shows how to use of response filter in  Java Servlet. Filter reads own initial parameters and adds its value
problem from registering a data in database with servlet - JSP-Servlet
problem from registering a data in database with servlet  Hi Rose, i created a servlet to validates ten user details in the database, if present it should return "You have already registered" but if not it should take all
Ext
; form example In this simplified application and easy to learn Ext Js Tutorial I will show you how to develop a form in Ext Js framework. The Ext Js form will take the input from user (in "register.html" file
SERVLET
request, HttpServletResponse response) throws ServletException, IOException...("empPassword"); String sql1="select PMSNUM_EMP_ID from PMST_EMP_MST
SERVLET
request, HttpServletResponse response) throws ServletException, IOException...("empPassword"); String sql1="select PMSNUM_EMP_ID from PMST_EMP_MST
q - JSP-Servlet
q  when a program run then the data is first retrieve from database and at runtime it save in .js file from that we show data in html control like... it should first clear the data from .js file and then reload the data again  
Server calling of .exe file in the client
Server calling of .exe file in the client   I have a requirement... I call a .exe file from client machine? I want to run .exe from webpage like servlet. any idea
Pass a dom object from jsp to servlet
Pass a dom object from jsp to servlet  I am creating a dom object in my jsp page. now i want to pass that object in a servlet through calling servlet in jsp. can anyone help me
Read Cookies from Servlet
Read Cookies from Servlet       This section illustrates you how to read cookies from Servlets. The Cookie Class... to retrieve all the cookies in your servlet program. This getCookies() method returns
JS-Sorcerer: JavaScript Development Tool
JS-Sorcerer: JavaScript Development Tool       JavaScript Reporter finds problems... features and benefits, and using it from the Windows Launcher, Eclipse plugin

Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.