Asynchronously call a remote web page without the complexity of AJAX

Let me first give me my scenario where I needed such a thing, so that it may clear what I mean by the title of this post.

Scenario:-
For a J2EE Online Library project of mine I needed to display a list of books that can be issued. Each book’s entry had a corresponding check box which when clicked by the user is added to the cart of the user. Now the list of items in cart is kept at server side which meant that I have to call a JSP page or a servlet from the client side without actually navigating to that page. This is usually accomplished using AJAX, which is not a trivial task. Hence, I devised simple trick.

The Trick:-
I thought if somehow I could load the called page into an iframe rather than the whole window then that will solve my problem, and it worked! Then make the iframe hidden. Below is the code snippet.

License: GNU Public License version 3.

Code:

[code lang=”html”]
<html>
<pre id="codebox-pseudo-ajax"><code>  <head>
    <title>Pseudo AJAX call trick by AppleGrew</title>
    <script type=’text/javascript’>
        function callUpdate(chkbox) {
                <strong>frames[‘proxy’].location.href = ‘ServletController?pg=updateCart&itemId=’ + chkbox.value + "&chosen=" + chkbox.checked;</strong>
                //alert(frames[‘proxy’].document.body.innerHTML); //Use to retrieve the value returned by ServletController.
        }
        </script>
  </head>
  <body>
            <br/>
            <br/>
            <br/>
            <br/>
            <br/>
            <center>
            <input name="itemId" type="checkbox" value="1" <strong>onclick="javascript:callUpdate(this);"</strong> /> Item1<br/>
            <br/>
            <input name="itemId" type="checkbox" value="2" <strong>onclick="javascript:callUpdate(this);"</strong> /> Item2<br/>
            </center>
           
           
            <!–The purpose of this iframe is to imitate a sort of AJAX call. The javascript calls the ServletController and
            the loaded page is loaded into this iframe w/o replacing the current page –>
            <strong><iframe id="proxy" name="proxy" style="display:none;"></iframe></strong>
  </body>
</html></code>[/code]

Where ServletController is the servelt controller of your project or just any other page. Note that if you need to retrieve any value returned from ServletController then it must return generated page as below.

<html>
<head></head>
<body>Put the value to be returned here.</body>
</html>

One Comment

Leave a Reply to Ntweat Cancel reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.