calling servlet from JS and return response from servlet to JS

calling servlet from JS and return response from servlet to JS

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 Tutorials/Questions & Answers:
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
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
Advertisements
calling servlet from jsp
calling servlet from jsp  how to call a servlet from jsp
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
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
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
Redirect from servlet to servlet
Redirect from servlet to servlet  I want to insert data from Text box... to redirectServlet , and from this servlet I want to again forward my page to insertServlet(i.e...; <servlet-name>redirectServlet</servlet-name> <servlet
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
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
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
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 .   ... the servlet mapping in web.xml: <servlet> <servlet-name>
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
JS - JSP-Servlet
the records from the table and display it in tabular form
how to fetch data from servlet ????
how to fetch data from servlet ????  how to fetch data from servlet
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
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
Navigate from jsp to servlet - JSP-Servlet
Navigate from jsp to servlet   Hi Friends, Sample code for Navigating a page from jsp to servlet. Thanks
ArrayList from JSP to Servlet - JSP-Servlet
ArrayList from JSP to Servlet  Hi, I have an arraylist declared in a scriplet in a jsp page. how can i access the arraylist in a servlet which...)); %> How can I access this arraylist in a servlet. How
Getting data from servlet into javascript
Getting data from servlet into javascript  How do i get json data from my servlet on to a variable in javascript n bind the data to display onto sigma grid.Has anyone Idea how to do
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
Java from JSP - JSP-Servlet
Calling Java from JSP  Does anyone have an example of Calling Java from JSP
redirect to multiple links from servlet
redirect to multiple links from servlet  hello , In my servlet page , i'm using response.redirect("www.somewebsiteaddress.com"); after it shows the output in browser,i need to redirect to another link like the above line. i
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
How to retrieve image from database in Servlet?
How to retrieve image from database in Servlet?  Hi, How to retrieve image from database in Servlet? Thanks   Hi, Please check the tutorial Retrieve image from database using Servlet. Thanks
How to pass an arraylist from servlet to jsp?
How to pass an arraylist from servlet to jsp?  Hello, Can anyone please tell me how to pass an arraylist from servlet to jsp? I have two arraylist one of type String and the other int. How to send both the arraylists from
retrieving from db - JSP-Servlet
retrieving from db  hello' I am trying to write my first application...: rst=stmt.executeQuery("select * from books_details"); 27: %> 28...; Hi Retrive value from database Retrive data from
Pass parameters from JSP to Servlet
Pass parameters from JSP to Servlet In this section, you will learn how to pass parameters from JSP page to servlet. For this purpose, we have used... is retrieved later in the servlet by passing the request object through
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
Getting Json data from servlet to javascript variable
Getting Json data from servlet to javascript variable  How do i get json data from my servlet on to a variable in javascript n bind the data to display onto sigma grid.Has anyone Idea how to do
How to carry multiple values from a Servlet to a JSP?
How to carry multiple values from a Servlet to a JSP?  By using the below code I am able to carry the username to a JSP (single value... needs to be carried from my servlet to a JSP. How do I do
How to pass multiple values from a servlet to JSP?
How to pass multiple values from a servlet to JSP?  hi, I want to pass multiple values form a servlet to JSP. Hw do i do that? I am able to send one value at a time without any prb, but I am unable to carry multiple (from two
How display a image on servlet from file upload - JSP-Servlet
How display a image on servlet from file upload   Dear Sir, My Question is: How display a image on servlet from file upload Your Answer: Hi... reason is inaccessible Thanks Sir, But Servlet page nothing display any type
get info from mysql using jsp and servlet
the user to key in their email address from mysql database by using servlet and jsp too...get info from mysql using jsp and servlet  HELLO! I wanna create... retrieved from database. 1)search.jsp: <html> <head> </head> <
retriving image from database - JSP-Servlet
retriving image from database  how to retrive image from mysql database by using servlet programming  Hi Friend, Please visit the following link: http://www.roseindia.net/servlets/retreiveimage.shtml Thanks
How to call jasper from jsp or servlet - JSP-Servlet
How to call jasper from jsp or servlet  Hi Expert , I created jasper report using ireport.how to call that jasper with jsp file or servlet file ? Thanks in advance Eswaramoorthy.s
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
Retrieve database from the table dynamically in jsp from oracle using servlet
using java servlet from the database in the jsp page...Retrieve database from the table dynamically in jsp from oracle using servlet  Sir, I have created a table in oracle using eclipse, and added few
How display a Image on servlet from file upload - JSP-Servlet
How display a Image on servlet from file upload  Dear Sir, I were ask a question that How display the Image on servlet through file upload. Today I get your answer. But Sir, It code not display the image on servlet
how to display a table from database using servlet
how to display a table from database using servlet  how to display a table with values from servletpage   Hi Friend, Please go through the following link:ADS_TO_REPLACE_1 http://roseindia.net/jsp/servlet-jsp-data
Fetching database field from servlet to jsp page ?
Fetching database field from servlet to jsp page ?  Hello Java... field. I wanted to pass some of the database field from servlet to jsp... (i am opening my database in servlet init() method ) how to pass rs.getString(8
How display a image on servlet from file upload - JSP-Servlet
How display a image on servlet from file upload  Dear Sir, My issue is: How display a image on servlet from file upload I receive your answer today... --------------------------------------------- Servlet action code
How to get jSon object in servlet from jsp - JSP-Servlet
How to get jSon object in servlet from jsp  How to get jSon object in servlet from jsp? In jsp page i have written: var sel... object in servlet???  Hi Friend, Please visit the following link
How to delete the row from the Database by using servlet
: Delete row from database using servlet   In that link solution...How to delete the row from the Database by using servlet  Dear Sir... by using servlet program (Tomcat server). The given data is true
getting values from database - JSP-Servlet
getting values from database  I tried the following code abc.html aaa.jsp I am not getting exceptions now... in Servlet. Thanks
How display a Image on Servlet from file upload - JSP-Servlet
How display a Image on Servlet from file upload  Dear Sir, My requirement is I want to display a Image on Servlet from File Upload. But It not display on servlet,Its appear a downloaded form and downloaded on disk when click
Invoke JavaScript function from servlet
Invoke JavaScript function from servlet You have learnt several servlet... function from the servlet. Embedding JavaScript in Servlets can be useful when... class Servlet extends HttpServlet { public void doGet
Uploading file in servlet from a html form
Uploading file in servlet from a html form  Sir, I want to upload a picture from my html file and save it to my database as BLOB,but what JAR should i use for this purpose i am really confused about.And also is it possible to do
Trouble in running Dos Command from Java Servlet
find the specified file. The above line of codes are in one servlet and from...Trouble in running Dos Command from Java Servlet  Hello All, I have to run following command from Java. The command is : vscanwin32 /S C:\Test > C

Ads