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.

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 lang=”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.
            <input name="itemId" type="checkbox" value="1" <strong>onclick="javascript:callUpdate(this);"</strong> /> Item1<br/>
            <input name="itemId" type="checkbox" value="2" <strong>onclick="javascript:callUpdate(this);"</strong> /> Item2<br/>
            <!–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>

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.

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

One Comment

Leave a 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.