Java Project JSP JDBC Java Program Core Java Demo MORE

Fetch or Retrieve data using ajax and JSP Java


Here we using 2 files for delete data in MySQL Database using Ajax:

  1. index.jsp:for get user input data
  2. fetch.jsp: A JSP file that process the request

index.jsp

<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div style="margin: auto;width:30%;padding-top:50px">
<form id="form1" name="form1" method="post">
<div class="form-group">
   
    <input type="text" class="form-control" placeholder=
    'Search by rollno...' id="roll_no"><br>
    <p align="center"><button type="submit" class="btn btn-primary btn-default" id="search">Submit</button></p><br>
    <label for="city">Display city name of student:</label>
    <input type="email" class="form-control" placeholder=
    'City name' id="city_name"><br><br>
    
  </div>
</form>
</div>
<script>
$("#search").click(function() {
         var roll_no= $('#roll_no').val();
         city_name.value = city_name; 
         $.ajax({
            url: "fetch.jsp",
            type: 'POST',
            data: {roll_no: roll_no},
            success: function(data) {
             
                 $('#city_name').val(data);
                 alert(data);
                  var city_name = data;
                  
                
            }
        });
    
});
   
</script>
</body>
</html>

fetch.jsp

<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%
String driver = "com.mysql.jdbc.Driver";
String connectionUrl = "jdbc:mysql://localhost:3306/";
String database = "student";
String userid = "root";
String password = "";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try{
String roll_no=request.getParameter("roll_no");
connection = DriverManager.getConnection(connectionUrl+database, userid, password);
statement=connection.createStatement();
String sql ="select city_name from users where roll_no="+roll_no;
resultSet = statement.executeQuery(sql);
int i=0;
while(resultSet.next()){
String city_name=resultSet.getString("city_name");
i++;
out.println(city_name);
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>