Friday 16 August 2013

How to use jQuery Ajax Function $.ajax() in jsp


<!--  Save as "testAjax.jsp"  -->

<script type="text/javascript" src="js/jquery-1.8.3.js"></script>

<script>
$(document).ready(function(){
/* Attach a submit handler to the form */
$("#submit").click(function(event) {

    var valBar = $("#bar").val();
alert($("#bar").val());
    /* Send the data using post and put the results in a div */
    $.ajax({
url: "testAjaxAction.jsp",
        type: "post",
        data: {'bar':valBar},
        success: function(data){
            //alert("success");
            //$("#result").html('Submitted successfully');
            $("#result").html(data);
        },
        error:function(data){
            //alert("failure");
            //$("#result").html('There is error while submit');
            $("#result").html(data);
        }
    });
});
});
</script>


    Enter Id
    <input id="bar" name="bar" type="text" value="" />
    <input type="submit" value="Send" id="submit"/>

<!-- The result of the search will be rendered inside this div -->
<div id="result"></div>

<!--------------------------------------------------------------------------------->

<!--  Save as "testAjaxAction.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">
<%@ page import="java.util.*" %>
<%@ page import="java.sql.*"  %>
<%@ page import="java.io.*" %>
<%@ page import="java.text.*"  %>
<%
Connection con = null; 
Statement stmt = null;
ResultSet rs = null;
%>
<%
String _class = "com.mysql.jdbc.Driver";
String _driver = "jdbc:mysql://localhost:3306/test";
String _user = "root";
String _pass = "public";
    Class.forName(_class);
    con = DriverManager.getConnection(_driver,_user,_pass);
    stmt = con.createStatement();
%>
<%
String bar = request.getParameter("bar");
if(request.getParameter("bar")!=null || request.getParameter("bar")!=""){
      request.getParameter("bar");       
}
try{  
String Query2 = "select username,password,url from cromext where id = '"+bar+"'";
rs = stmt.executeQuery(Query2);
while(rs.next()){
%>
 <table>
      <tr>
         <td><strong>UserName:</strong> <input type="text" name="username" id="username" value="<%=rs.getString(1)%>" size="30"/></td>
      </tr>
      <tr>
         <td><strong>Password:</strong> <input type="password" name="password" value="<%=rs.getString(2)%>" id="password" size="30"/></td>
      </tr>
      <tr>
         <td><strong>Url:</strong> <input type="text" name="url" id="url" value="<%=rs.getString(3)%>" size="50"/></td>
      </tr>
  </table>
<%}
}
catch(Exception ex){
out.println("Unable to process data..."+ex);
}
    finally{
    rs.close();
    stmt.close();
    con.close();
    }
    %>



No comments:

Post a Comment