Monday 12 June 2017

Tutorial of JSP AJAX

AJAX INTRODUCTION :

Ajax stands for Asynchronous JavaScript and XML. Basically Ajax is not a programming language but it is a technique for using JavaScript. Basic features of Ajax are:

1. You can download any file in the background process from the web server.
2. User can dynamically update any page without the waiting by the user.
3. Web pages can be easily updated without reloading the current page.
4. It can request date from the server after the page has been loaded.
5, It can receive data from the server after the page has been loaded.
6. It can send the data to the server at the background.
7. Ajax is a web browser technology independent of web server software.
8. To get the data from the server you don't even have to click the button, you can just move your mouse for the action.

XMLHttpRequest Object:
XMLHttpRequest is the object to get the data from the server, it can get the information from the server without reloading the page.

Creating XMLHttpRequest Object: Basically all the browsers have built-in XMLHttpRequest Object. The syntax for creating XMLHttpRequest Object is:

var h= new XMLHttpRequest();

XMLHttpRequest Methods: There are various methods that can be used with XMLHttpRequest Object, Some of these are:

1. open
2. send
3. setRequestHeader
4. abort
2. getAllResponseHeaders
3. getResponseHeader 

XMLHttpRequest Properties:

1. onreadystatechange
2. readyState
3. responseText
4. responseXML
5. status

Sending Request to server:

var h=new XMLHttpRequest();
h.open("GET","data.jsp",true);
h.send();

There are two methods that we can used for sending the information to the server. The two methods are Get and Post methods, these two methods are used for sending request to the server. There is basically some differences between using Get and Post method. These differences are given below:

1. Post method is preferred always where we want to submit the data to the server.
2. Post method is used where the amount of data to be sent is large or enough.
3. Post method is used because it is secure.

You can used Post method as:

var h=new XMLHttpRequest();
h.open("POST","data.jsp",true);
h.send();

The parameter used in h.open() method are method whether it is GET or Post, then the url of the page and last parameter is async. async parameter must be set to true because it helps in sending request to the server. If you set it to false the server will not respond to the request or the server will just hang up.

Example:

HTML Page:

<html>
    <head>
        <title>TODO</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script>
        function load()
        {
            var h=new XMLHttpRequest();
            h.onreadystatechange=function()
        {
                if(this.readyState==4 && this.status==200)        
        {
            document.getElementById("res").value=this.responseText;
        }
        };
            var var1=document.getElementById("b1").value;
            var var2=document.getElementById("b2").value;  
            h.open("GET","data.jsp?v1="+var1+"&v2="+var2,true);  
            h.send();
        }
    </script>
    </head>
    <body>
        <h1>AJAX EXAMPLE</h1>
        First Value:<input name="i1" type="text" id="b1">
        Second Value:<input name="i2" type="text" id="b2">
        <button type="button" onclick="load()">button</button>
       <br><br><br>
        <div id="he">
        Result Value:<input name="i3" type="text" id="res">
        </div>
    </body>

</html>

JSP Page:

        <%
        int a=Integer.parseInt(request.getParameter("v1"));
        int b=Integer.parseInt(request.getParameter("v2"));
        int c=(a+b);
        out.println(c);
        %>

The above example is basically doing the sum operation or addition. We have to enter the two values for getting the result that is sum. After entering the values when we press the button, then the load() function will be triggered which applied on onclick function(). Then it will goes to the load() function XMLHttpRequest Object is created. The values from the both the input text is fetched and is stored in variables, then these values are passed to the data.jsp page on which addition operation is performed. Then there is one property name  h.onreadystatechange=function(), and if the condition is satisfied the result will be printed to the input box having id =res. Ajax will print the result on same page on input box without actually reloading the page.

Screenshot:

Tutorial of JSP AJax in java
Tutorial of JSP AJax in java

Another Example of Ajax: This program will print the records fetched from the database.

HTML Page:

<html>
    <head>
        <title>TODO supply a title</title>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">  
        <script>
            function load()
            {
                var b=document.getElementById("t1").value;
                var h=new XMLHttpRequest();
                h.onreadystatechange=function()
                {
                    if(this.readyState==4 && this.status==200)
                    {                  
                        document.getElementById("abc").innerHTML=this.responseText;
                    }              
                };
                h.open("GET","fetch_data.jsp?v1="+b,true);  
                h.send();      
    }
        </script>
       </head>
    <body>
        <center><h1>FETCHING RECORDS USING AJAX</h1></center>
        <div id="abc">
            <input type="text" name="t3" id="t1"/>
            <button type="button" id="b1" onclick="load()">FETCH RECORDS</button>
        </div>
    </body>
</html>

JSP Page:

<%--
    Document   : data1
    Created on : Jan 19, 2017, 2:59:49 PM
    Author     : Bsb
--%>

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.Connection"%>
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <table align="center" bordercolor="green" border="4" cellpadding="2" cellspacing="5"          bgcolor="red" width="250" height="250">
        <tr>
            <th>
                Name
            </th>
            <th>
                Subject
            </th>
            <th>
                Marks
            </th>
        </tr>
        <%
        Class.forName("com.mysql.jdbc.Driver");
        Connection co=DriverManager.getConnection("jdbc:mysql://localhost/virtuoso","root","aaron");
        Statement s=co.createStatement();
        String s1=request.getParameter("v1");
        ResultSet rs=s.executeQuery("Select * from student where Name='"+s1+"'");
        while(rs.next())
        {
        String s2=rs.getString(1);
        String s3=rs.getString(2);
        String s4=rs.getString(3);
        %>
        <tr>
            <td><%out.print(s2);%></td>
            <td><%out.print(s3);%></td>
            <td><%out.print(s4);%></td>
        </tr>    
        <%
        }
        %>  
        </table>
    </body>

</html>

Screenshot:

Tutorial of JSP AJax in java
Tutorial of JSP AJax in java

No comments:

Post a Comment

Oracle / PLSQL: FOR LOOP

set serveroutput on; declare a1 varchar2(100); begin select count(*) into a1 from employees; for i in 1..a1 loop dbms_output.put_line...