Saturday, January 21, 2012

Replacing page contents completely using javascript

Let me share with you an example of how it is possible to replace the whole page content using javascript. When this is applicable? One of the situations I have experienced was the requirement to call a third party service returning the whole report content as a HTML page. Report generation was quite a time consuming operation and because of that reason there was a requirement to call the service using Ajax.

The complete solution:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
    <head>
        <title>Calling a long running page</title>
        <script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
        
        <script type="text/javascript">
            $(document).ready(function () {
                $.ajax({
                    url: "LongRunningPage.aspx",
                    type: "POST",
                    context: document,
                    data: {
                        parameter1: "This is parameter1 value"
                    },
                    success: function (data) {
                        document.open();
                        document.write(data); 
                        document.close(); 
                    }
                });
            }
            );
        </script>

    </head>
    <body>
        <p><img src="ajax-loader.gif" alt="In progress" /></p>
    </body>
</html>

By the way, I highly recommend this site if you need a progress info image for ajax calls.

No comments:

Post a Comment