Click here to Skip to main content
11,706,455 members (47,288 online)
Click here to Skip to main content
Articles » Web Development » Ajax » General » Revisions

Ajaxion - Standalone Ajax - Part 2 of 2 - C# and Java Example

, 8 Jul 2008 CPOL 36.8K 1.3K 42
Rate this:
Please Sign up or sign in to vote.
An article about how to keep Ajax simple as it is and get the most out of it
This is an old version of the currently published article.
Screenshot - Screenshot.jpg

Introduction

This article was initially about "keeping JavaScript simple"... unless you have no choice. The best productivity and results are based on understanding, they do not necessarily rely on heavy frameworks and technologies... maybe on standards.

Part 1 of this article is about how Standalone Ajax can improve SDLC: Agile, Web design, server side.

Ajax can provide great advantages for Web applications, so why not promote Ajax to be a standalone technology? Why use it mostly as a helper for the existent Web technologies like ASP, JSP, JSF, PHP...? Why not cut out most of the "X Server Pages" layers - used to render "dynamically a lot of static content"?

Part 1 of this article presents more aspects about how "Standalone Ajax" can improve the software life cycle: Agile methodology, Web design - facing customers quickly, server side, reliability, scalability, load balancing; right now let's just take a look, with your permission, inside this wrapper of the browser object that does all the magic - XmlHttpRequest; let's just taste this magic alone and not through the old style frameworks.

Background

The .NET sources contain the Ajaxion embedded into an ASP.NET application; it was the first approach; for the Standalone Ajax follow the "Standalone Ajax demo" link. The Java source contains only the Standalone Ajax demo (by the way, the subject is Standalone Ajax not .NET vs. Java). The ajaxion.js is the same in both, the page event handlers. *.js follow the same idea, the server-side is... a bit different - C#, Java... "a bit" because the server side is already service oriented - that is much more important than the language: the .NET server side relies mostly on a Web service, the Java server side is a service-servlet. The Java HTTP servlets are the very simple renderings of HTML, XML or whatever - emphasizing the service approach, running on the application server (you can deploy on Tomcat - for coding, the Oracle JDeveloper have been used).

The idea is well known: an Ajax JavaScript layer acts between the "Ajax enabled" page (its HTML, in fact, even if it is rendered by some ASP or JSP or PHP...) in the browser and the Web (app) server. The Ajaxion JavaScript layer defines Ajaxion events enclosing Ajax calls to the Web (app) server. The Web server runs some C# or Java code to consume the Ajaxion events (their Ajax calls). Instead of having Ajax calls, we can design the server side to consume other services as well, we are almost there, close to a better structure and interoperability across the enterprise... right from the start. The Ajaxion JavaScript layer uses XmlHttpRequest to make "HTTP calls". These calls are nearly the same POST or GET but call service like functionality, asynchronously with the normal host page life-cycle.

What if we have the Ajax standalone - in a simplified vision: static XHTML, JavaScript Ajax call layer, HTTP, service oriented server-side? Why not, let's think to DLR, how powerful will a dynamic language based application be, bringing maybe a lot of "highly responsive smart client flavour" in the enterprise, rather than the now-a-days Web applications... dying under heavy viewstates or bloated sessions. It is "cool" to bind together so many languages... but... even if most programmers like C# many applications are a mixture of C# and VB.NET, carrying on the VB6 and ASP legacy. On the .NET platform now, you need to know "more languages than technologies" - Python, Ruby etc. are really coming in - .NET is still in its youth; in Java you need to know mostly standards like EJB, the core being well proven, compact and stable... facing now the rise of dynamic languages... So let's build the applications of tomorrow using the current standards... with no learning curve!

A Short Guide for the Code

Ajaxion relies on:

  • ajaxion.js - that hosts a class like JavaScript that initiates the Ajax calls
  • The rest of *.js defines the Ajaxion events hosting the Ajax calls and their callback JavaScript functions - used to update the host page target HTML elements
  • The C# / Java class AjaxionEventConsumer that handles the Ajaxion events (their Ajax calls) on the server side

How to Get an Ajax Enabled HTML Element by using Ajaxion

Register the Ajaxion JavaScripts to be used in the host page, e.g. see head of Default.aspx. Choose an XHTML element event to trigger the Ajaxion events, like onclick (you can register them also in the body onload):

onclick="ajaxion.postUrl('AjaxCallbackWs.asmx/GetImageUrl', 'imageUrl', GetImageUrl)"

// or e.g. set the HTML event from the C# class of the host page
btnAjaxWsGetImgUrl.Attributes.Add("onClick",
    "ajaxion.postUrl('AjaxCallbackWs.asmx/GetImageUrl',
    'imageUrl', GetImageUrl)");

// be aware, the both above methods were used

//or use body onload (in the Java example):
function onLoad()
{
   var handler = "ajaxion.get('getText', getTextCallback)";
   window.document.getElementById("btn").setAttribute("onclick", handler);
}

and in the page:
<body onload="onLoad()" ...

Register the Ajaxion event (e.g. imageUrl) and the callback function (e.g. GetImageUrl) in the host page specific script (e.g. DefaultAspx_AjaxionEvents.js)

// Register Ajaxion event "imageUrl"

function parseEventParam(eventId)
{
    ajaxion.beginEvent(eventId);
    var parameters = '';

    switch (eventId)
    {
        ...
        case 'imageUrl' :
            ajaxion.setEventMonior('imageUrl', '');
            parameters = window.document.getElementById('dropDown').value;
            break;
        ...
    }
    return parameters;
}

// You can override functions from ajaxion.js like:
// Override ajaxion.beginEvent for the current page
ajaxion.beginEvent = beginEvent;
function beginEvent(eventId)
{
   // Page specific code
}

// Ajaxion event "imageUrl" callback function.
// This updates the host page after the Ajax call for the
// Ajaxion event was consumed.

function GetImageUrl()
{
    if (ajaxion.isEventConsumed())
    {
        window.document.getElementById('image').src = ajaxion.request.responseText;
        window.document.getElementById('image').title = ajaxion.GetParameters();
        ajaxion.endEvent();
    }
}

And, last but not least, the C# / Java code to consume the Ajaxion event:

[WebMethod]
public void GetImageUrl()
{
   try
    {
        AjaxionEventConsumer consumer = new AjaxionEventConsumer(this.Context, 700);
        consumer.ConsumeEvent("images/" + consumer.Parameters, "text/html");
    }
    catch (System.Threading.ThreadAbortException)
    {}
    catch (Exception ex)
    {
        FileLog.WriteLogLn("\nException: " + ex.Message + "\nTrace: " + ex.StackTrace);
    }
}

// Or the Java code:
public void service(HttpServletRequest request, HttpServletResponse response)
{
    try
    {
        if (consumer == null)
            consumer = new AjaxionEventConsumer(request, response, 1000);
        else
            consumer.init(request, response, 1000);

        String eventId = consumer.getEventId();
        String param = consumer.getParameters();
        String contentType = "text/html; charset=windows-1252";

        if (eventId.equals(GET_TEXT))
        {
           consumer.beginResponse(contentType);
           consumer.respondString("ajaxionTest.sevice handled POST or GET");
           consumer.respondString(eventId + " [ " + param + " ]");
           consumer.endResponse();
        }
        else
           consumer.consumeEvent("ajaxionTest.sevice handled an event", contentType);

         String message = "ajaxionTest.sevice handled : " + eventId + " 
                    [ " + param + " ]";
         System.out.println(message);
         FileLog.WriteLn(new FileLog().getFileName(), message);
    }
   catch (Exception ex)
   {
        String message = "ajaxionTest.sevice exception : " + ex.getMessage();
        System.out.println(message);
        FileLog.WriteLn(new FileLog().getFileName(), message);
   }
}

Points of Interest

The functionality demonstrated is (in the order it appears):

  • The exchange of some text between two text boxes, but the Ajaxion calls are targeted to different URL-s- pages and WS
  • An XML test, using a Web service call. It is convenient here (unless there is no choice) to handle XML in C# / Java rather than in JavaScript where, as always we run into browser incompatibilities - so let's just keep it simple
  • An approach to start and monitor a thread running on the server
  • Some image retrieval
  • Some drag'n drop
  • And, last but not least, a user control demo, a good approach for Ajaxion, Ajaxion being mostly the XmlHttpRequest wrapper foundation and not the ultimate Web UI fancy effects provider
  • For now, this may look less convenient than the easy usage of e.g. MagicAjax (which is great, by the way) but the point here is to eliminate the "X"SP layer so the server side is responsible much more for the logic instead of rendering XHTML... and... you have complete control over the entire Ajax roundtrip without needing to hook in and recompile any library code; so just keep the event handler JavaScript simple. In time, I will update this article to simplify the code and provide a shorter way to use control-like features as "X"SP have controls / custom tags.

Hope this helps.

History

  • 8th July, 2008: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

radumi
Software Developer
New Zealand New Zealand
Coder

You may also be interested in...

Comments and Discussions


Discussions posted for the Published version of this article. Posting a message here will take you to the publicly available article in order to continue your conversation in public.
 
GeneralMy vote of 5 Pin
Md. Marufuzzaman21-Jan-13 22:08
mentorMd. Marufuzzaman21-Jan-13 22:08 
Question:) Pin
pty3452-Jan-12 14:08
memberpty3452-Jan-12 14:08 
QuestionQuick one Pin
draffa213-May-10 20:46
memberdraffa213-May-10 20:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150819.1 | Last Updated 8 Jul 2008
Article Copyright 2008 by radumi
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid