Html inside Another HTML – Ajax + Jquery
Today, In this article we are going to see how to load a html/jsp file into another file using ajax.

Many applications make use of Ajax for loading form/file dynamically in the same page to improve performance of the application. When a user selects the option from drop-down box or when user clicks a button etc. We may be required to load or show a Html/Jsp/Forms based on the user input or when user performs any action.

So let us see an example code about how to load a JSP/HTML file within another JSP/HTML file.

Let us create 2 JSP files for this example,

form1.jsp

<%@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>
        <h1>This is a sample text to be displayed</h1>
    </body>
</html>

We are just creating a sample text in form1.jsp
Now we are going to bring this form1.jsp into form2.jsp when user clicks a button

<html>
    <head>
        <title>Registration Form </title>
        <script src="https://code.jquery.com/jquery-1.11.3.js"></script>
         <script>
            function Ajax() {
            $.ajax({
                    url: 'form1.jsp',
                    dataType: 'html',
                    timeout: 500, 
                    success: function(html) {
                    $("div").html(html);
                    }
                    });
                }
        </script>
    </head>
    <body>
            <input type="button" value="Click Here" onclick="Ajax()">
        <div>   
        </div>
    </body>
</html>

From the above code, We are using ajax and we are setting the URL of form1.jsp and we are setting its type (html). We are setting the time for the form1 to be displayed and if url and datatype is success, then it will get displayed inside <div> </div>

Output:
op1
On clicking the button,
op2

By Sri

Leave a Reply

Your email address will not be published. Required fields are marked *