Computer Science, asked by Lathwal8327, 1 year ago

How to send request on server without refreshing the page in jsp?

Answers

Answered by Anonymous
5
. index.jsp holds the HTML form for submitting the data to the input.jsp. Internally the form data is collected by the javascript side of the page and submitted to input.jsp without refreshing the page.

index.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script type="text/javascript"> function take_values(){ var n=document.forms["myform"]["name"].value; if (n==null || n=="") { alert("Please enter User Name"); return false; }else{ var http = new XMLHttpRequest(); http.open("POST", "http://localhost:8080/Submit_Form/input.jsp", true); http.setRequestHeader("Content-type","application/x-www-form-urlencoded"); var params = "param1=" + n; // probably use document.getElementById(...).value http.send(params); http.onload = function() { alert(http.responseText); } } } </script> </head> <body> <center> <form name="myform" > Name <input type="text" name="name"> <br> <input type="button" value="Submit" onclick="return take_values()"> </form> </center> </body> </html>

3. input.jsp holds code to collect the parameters forwarded from index.jsp and insert into table.
input.jsp

<%@page import="java.sql.Statement"%> <%@page import="java.sql.SQLException"%> <%@page import="java.sql.DriverManager"%> <%@page import="java.sql.Connection"%> <% String name=(String)request.getParameter("param1"); out.println(name+" Added Succesfully"); Connection connection=null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root", "root"); String query="insert into codes(name) values('"+name+"')"; Statement st=connection.createStatement(); st.executeUpdate(query); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } %>

4. After running the project in local host server. The index.jsp will be looking like,


5. After successful insertion the alert will be generated from input.jsp and it will be displayed in index.jsp


6. MySql table after insertion of data in the table.

Similar questions