Nav
You are viewing an older version of this section. Click here to navigate to the latest version.

Ajax Transport Reference

Ajax (Asynchronous Java and XML) is a group of interrelated web development techniques used for creating interactive web applications or rich Internet applications. With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page.

The Mule Ajax connector allows Mule events to be sent and received asynchronously to and from the web browser. The connector includes a JavaScript client that listens for events, sends events, and performs RPC calls. It can be deployed in Mule standalone or embedded in a servlet container such as Apache Tomcat or Tcat Server.

Ajax Connector Guide: Ajax Connector

Transport Info

Feature Value Description

Transport

Ajax

The name/protocol of the transport

Doc

JavaDoc and Schema doc

Inbound

check

Whether the transport can receive inbound events and can be used for an inbound endpoint.

Outbound

check

Whether the transport can produce outbound events and be used with an outbound endpoint.

Request

error

Whether this endpoint can be queried directly with a request call (via MuleClient or the EventContext).

Transactions

error

Whether transactions are supported by the transport. Transports that support transactions can be configured in either local or distributed two-phase commit (XA) transaction.

Streaming

check

Whether this transport can process messages that come in on an input stream. This allows for very efficient processing of large data.

Retries

error

Whether this transport supports retry policies. Note that all transports can be configured with Retry policies, but only the ones marked here are officially supported by MuleSoft.

MEPs

one-way

Message Exchange Patterns supported by this transport.

Default MEP

one-way

The default MEP for endpoints that use this transport that do not explicitly configure a MEP

Maven Artifact

org.mule.transport:mule-transport-ajax

The group name and artifact name for this transport in Maven

The Ajax transport has server and client parts. The server part is similar to every other Mule transport. The client part is a JavaScript client that lets users publish and subscribe to Mule messages in a browser (see Using the JavaScript Client). The server connector can either run as an embedded Ajax (cometD) server or bind to a servlet container.

Namespace and Syntax

XML Namespace:

xmlns:ajax="http://www.mulesoft.org/schema/mule/ajax"

XML Schema location:

http://www.mulesoft.org/schema/mule/ajax http://www.mulesoft.org/schema/mule/ajax/current/mule-ajax.xsd

Connector Syntax:

<ajax:connector name="ajaxServer" serverUrl="http://0.0.0.0:8090/mule/ajaxServer" resourceBase="${app.home}/docroot"/>

Endpoint Syntax

  1. Inbound endpoint:

    <ajax:inbound-endpoint channel="/services/someAjaxService" />
  2. Outbound endpoint:

    <ajax:outbound-endpoint channel="/mule/notifications" cacheMessages="true"/>

Considerations

You should use the Mule Ajax Transport for bi-directional communication with a browser. Under the covers it uses CometD, which enables higher numbers of concurrent requests and optimized server resource usage.

Features

  • Easily performs asynchronous calls to Mule

  • Broadcasts events to browsers listening to Ajax channels

  • Performs sudo - RPC calls from the browser

  • Uses standalone or bound to a servlet container

Usage

To the Ajax transport in your configuration, add the ajax namespaces:


         
      
1
2
3
4
5
6
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:ajax="http://www.mulesoft.org/schema/mule/ajax"
      xsi:schemaLocation="
        http://www.mulesoft.org/schema/mule/ajax http://www.mulesoft.org/schema/mule/ajax/current/mule-ajax.xsd
        http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">
...

Configuring the Server

The usual way of setting up the Ajax server is to use the one embedded in Mule. This can be created by adding an ajax:connector element to your config:

<ajax:connector serverUrl="http://0.0.0.0:8080/ajax"/>

This starts an Ajax server and is ready to start publishing and subscribing. Next you can create a flow that listens to Ajax messages on a channel:


          
       
1
2
3
4
<flow name="AjaxEcho">
    <ajax:inbound-endpoint channel="/services/echo"/>
    <echo-component/>
</flow>

Or to publish on an Ajax channel, use an outbound endpoint:

Embedding in a Servlet Container

If you are running Mule inside a servlet container such as Apache Tomcat, bind Ajax endpoints to the servlet container by adding the org.mule.transport.ajax.container.MuleAjaxServlet to your web.xml in your webapp and use the ajax:servlet-xxx-endpoint elements.

Configure your web.xml using:


          
       
1
2
3
4
5
6
7
8
9
10
<servlet>
    <servlet-name>ajax</servlet-name>
    <servlet-class>org.mule.transport.ajax.container.MuleAjaxServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>
 
<servlet-mapping>
    <servlet-name>ajax</servlet-name>
    <url-pattern>/ajax/*</url-pattern>
</servlet-mapping>

Then replace any ajax:inbound-endpoint and ajax:outbound-endpoint with ajax:servlet-inbound-endpoint and ajax:servlet-outbound-endpoint respectively.

To use the football scores example again:


          
       
1
2
3
4
<flow name="AjaxBridge">
    <jms:inbound-endpoint topic="football.scores"/>   
    <ajax:servlet-outbound-endpoint channel="/football/scores"/>
</flow>

Then configure your connector and endpoints as described below.

Using the JavaScript Client

Mule provides a powerful JavaScript client with full Ajax support that can be used to interact with Mule flows directly in the browser. It also provides support for interacting directly with objects running inside the container using Cometd, a message bus for Ajax web applications that allows multi-channel messaging between the server and client.

Configuring the Server

To use the JavaScript client, you just need to have a flow that has an Ajax inbound endpoint through which requests can be sent. This example shows a simple echo flow published on the /services/echo Ajax channel:


          
       
1
2
3
4
<flow name="AjaxEcho">
    <ajax:inbound-endpoint channel="/services/echo"/>
    <echo-component/>
</flow>

Enabling the Client

To enable the client in an HTML page, add a single script element to the page:


          
       
1
2
3
<head>
  ...
  <script type="text/javascript" src="mule-resource/js/mule.js"></script>

Adding this script element makes a 'mule' client object available for your page.

Making an RPC request

This example defines a button in the body that, when clicked, sends a request to the Echo flow:

<input id="sendButton" class="button" type="submit" name="Go" value="Send" onclick="callEcho();"/>

The button calls the callEcho function, which handles the logic of the request:


          
       
1
2
3
4
5
6
function callEcho()
{
  var data = new Object();
  data.phrase = document.getElementById('phrase').value;
  mule.rpc("/services/echo", data, callEchoResponse);
}

This function uses the rpc method to request data from the flow. The rpc method sets up a private response channel that Mule uses to publish when response data is available. The first argument is the channel on which you’re making the request (this matches the channel that our Echo Flow is listening on), the second argument is the payload object, and the third argument is the callback function that processes the response, in this case a function called call Echo Response:


          
       
1
2
3
4
function callEchoResponse(message)
{
    document.getElementById("response").innerHTML = "<b>Response:&nbsp;</b>" + message.data + "\n";
}

If you use rpc just for a one-way request where you don’t pass a callback function as parameter because you don’t expect a response, use the disableReplyTo flag in the Ajax connector:

<ajax:connector name="ajaxServer" ... disableReplyTo="true" />

Handling Errors

To check if an error occurred, set the error parameter in the callback function to verify that the error is null before processing. If it is not null, an error occurred and the error should be logged or displayed to the user.


           
        
1
2
3
4
5
6
7
8
9
10
11
function callEchoResponse(message, error)
{
  if(error)
    handleError(error)
  else
    document.getElementById("response").innerHTML = "<b>Response:&nbsp;</b>" + message.data + "\n";
}
 
function handleError(error) {
   alert(error);
}

Listening to Server Events

The Mule JavaScript client allows developers to subscribe to events from Mule flows. These events just need to be published on an Ajax endpoint. Here is a flow that receives events on JMS and publishes them to an Ajax channel.


         
      
1
2
3
4
5
<flow name="AjaxBridge">
    <jms:inbound-endpoint topic="football.scores"/>
     
    <ajax:outbound-endpoint channel="/football/scores"/>
</flow>

Now you can register for interest in these football scores by adding a subscriber via the Mule JavaScript client.


         
      
1
2
3
<script type="text/javascript">
    mule.subscribe("/football/scores", scoresCallback);
</script>

The first argument of the subscribe method is the Ajax path that the flow publishes to. The second argument is the name of the callback function that processes the message. In this example, it’s the scoresCallback function, which is defined next:


         
      
1
2
3
4
5
6
7
8
9
10
11
12
13
function scoresCallback(message)
{
    console.debug("data:" + message.data);
 
    if (!message.data)
    {
        console.debug("bad message format " + message);
        return;
    }
 
    // logic goes here
    ...
}

JSON Support

Mule has JSON support including object/JSON bindings, which makes it really easy to marshal data to JSON markup before dispatching to the browser, where JSON is a native format.

Sending a Message

Let’s say you want to send a message out without getting a response. In this case, you call the publish function on the Mule client:


         
      
1
2
3
<script type="text/javascript">
    mule.publish("/services/foo", data);
</script>

Example Configurations

Mule comes bundled with several examples that employ the Ajax Connector. We recommend you take a look at the "Notifications Example" and the "GPS Walker Example" (which is also explained in further detail in this blog post). In the following typical use cases we focus on the key elements involved when using and configuring the connector.

Publish Example Server code

First, set up an Ajax inbound endpoint in the Mule configuration to receive requests:

Configuring an Ajax Inbound Endpoint

               
            
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:ajax="http://www.mulesoft.org/schema/mule/ajax" (1)
      xsi:schemaLocation="
        http://www.mulesoft.org/schema/mule/ajax http://www.mulesoft.org/schema/mule/ajax/current/mule-ajax.xsd (2)
        http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">
 
    <ajax:connector name="ajaxServer" serverUrl="http://0.0.0.0:8090/services/updates"
        resourceBase="${app.home}/docroot"/> (3)
 
    <flow name="TestNoReply">
        <ajax:inbound-endpoint channel="/services/serverEndpoint" /> (4)
        <!-- From here on, the data from the browser is available in Mule. -->
        ...
        <component .../>
    </flow>
 
</mule>
1 The Mule AJAX namespace was added to the mule element.
2 Mule schema location was added to mule element.
3 The AJAX Connector creates an embedded AJAX server for this application. The ‘resourceBase’ attribute specifies a directory where HTML and other resources can be published. When the browser requests pages, pages serve from this location. The ${app.home} placeholder references the root directory of your application. 0.0.0.0 is the IP address of the computer running the Mule instance.
4 An AJAX inbound endpoint was added to a sample flow. This creates a channel named /services/serverEndpoint and listens to incoming messages from the Mule JavaScript client.

Publish Example Client Code

The browser sends some information to Mule (using the JavaScript Mule client) when a button is pushed.

Publishing data

               
            
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<head>
    <script type="text/javascript" src="mule-resource/js/mule.js"></script> (1)
    <script type="text/javascript">
     
        function publishToMule() { (2)
            // Create a new object and populate it with the request data
            var data = new Object();
            data.phrase = document.getElementById('phrase').value;
            data.user = document.getElementById('user').value;
            // Send the data to the Mule endpoint and do not expect a response.
            // The Mule element is provided by the Mule JavaScript client.
            mule.publish("/services/serverEndpoint", data); (3)
        }
    </script>
</head>
 
<body>
    <div>
        Your phrase: <input id="phrase" type="text"/>
        <select id="user">
            <option value="anonymous">Anonymous</option>
            <option value="administrator" selected="true">Administrator</option>
        </select>
        <input id="sendButton" class="button" type="submit" name="Go" value="Send" onclick="publishToMule();"/>
    </div>
 
</body>
1 Loading the mule.js script makes the Mule client automatically available via the ‘mule’ variable.
2 The rpcCallMule() method gathers some data from the page and submit it to the ‘/services/noReplyEndpoint’ channel we configured beforehand.
3 The mule.publish() method makes the actual call to Mule. It receives a channel name and the data to publish.

Subscribe Example Server code

This is a useful and friendly way to send information to several clients at once. All they have to do is subscribe themselves to a channel where the server sends whatever needs to be broadcasted.

Mule Runtime provides an AJAX connector, an AJAX outbound endpoint and the required JavaScript client library to take care of this.

We add an AJAX connector that hosts the pages (HTML, CSS, etc.) using the JavaScript client and that lets them interact with Mule’s AJAX endpoints. It’s the same connector we used in the two previous examples.

We also need to publish some content via an AJAX outbound endpoint in a channel.

Configuring an AJAX Outbound Endpoint Channel

               
            
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:ajax="http://www.mulesoft.org/schema/mule/ajax" (1)
      xsi:schemaLocation="
        http://www.mulesoft.org/schema/mule/ajax http://www.mulesoft.org/schema/mule/ajax/current/mule-ajax.xsd (2)
        http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">
 
    <ajax:connector name="ajaxServer" serverUrl="http://0.0.0.0:8090/services/updates"
        resourceBase="${app.home}/docroot"/> (3)
 
    <flow name="PublishUpdates">
        <!-- ... here we create the content to be published -->
        <ajax:outbound-endpoint channel="/mule/notifications" cacheMessages="true"/> (4)
    </flow>
 
</mule>
1 The Mule AJAX namespace was added to the mule element.
2 The AJAX schema location was added to the mule element.
3 The AJAX Connector creates an embedded Ajax server for this application. The ‘resourceBase’ attribute specifies a directory where HTML and other resources can be published. When the browser requests pages, pages serve from this location. The ${app.home} placeholder references the root directory of your application. 0.0.0.0 is the IP address of the computer running the Mule instance.
4 An AJAX outbound endpoint was added to a sample flow, which submits the events it receives into a channel named /mule/notifications, and any page listening on that channel receives a copy of the event.

Subscribe Example Client Code

Listening to an AJAX Outbound Channel

               
            
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<head>
    <script type="text/javascript" src="mule-resource/js/mule.js"></script> (1)
 
    <script type="text/javascript">
    
        function init() (2)
        {
            mule.subscribe("/mule/notifications", notif);
        }
 
        function dispose() (3)
        {
            mule.unsubscribe("/mule/notifications", notif);
        }
 
        function notif(message) (4)
        {
            console.debug("data:" + message.data);
 
            //... code to handle the received data
        }
     
    </script>
</head>
 
<body onload="init()" onunload="dispose()"> (5)
 
</body>
1 Loading the mule.js script makes the Mule client automatically available via the mule variable.
2 The init() method associates all incoming events on the /mule/notifications with the notif() callback method.
3 The dispose() method dissociates all incoming events on the /mule/notifications from the notif() callback method.
4 The notif() callback method processes the received messages.
5 The onload and onunload attributes of the body HTML element should contain the calls to init() and dispose() respectively, to ensure the page is properly registered and de-registered to the /mule/notifications channel.

RPC Example Server Code

This configuration is very similar to the one in the previous example. As a matter of fact, the only significant changes are the channel name and an out-of-the-box echo component to bounce the request back to the caller.

Configuring an AJAX Inbound Endpoint that sends a response

               
            
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<mule xmlns="http://www.mulesoft.org/schema/mule/core"
      xmlns:ajax="http://www.mulesoft.org/schema/mule/ajax" (1)
      xsi:schemaLocation="
        http://www.mulesoft.org/schema/mule/ajax http://www.mulesoft.org/schema/mule/ajax/current/mule-ajax.xsd (2)
        http://www.mulesoft.org/schema/mule/core http://www.mulesoft.org/schema/mule/core/current/mule.xsd">
 
    <ajax:connector name="ajaxServer" serverUrl="http://0.0.0.0:8090/services/updates"
        resourceBase="${app.home}/docroot"/> (3)
 
    <flow name="TestEcho">
        <ajax:inbound-endpoint channel="/services/echo" /> (4)
        <echo-component/>
    </flow>
 
</mule>
1 The Mule AJAX namespace was added to the mule element.
2 The Mule AJAX schema location was added to the mule element.
3 The AJAX Connector creates an embedded AJAX server for this application. The ‘resourceBase’ attribute specifies a directory where HTML and other resources can be published. When the browser requests pages, they are served from this location. The ${app.home} placeholder references the root directory of your application. 0.0.0.0 is the IP address of the computer running the Mule instance.
4 An AJAX inbound endpoint was added to a sample flow. This creates a channel named /services/echo that listens to incoming RPC calls from the Mule JavaScript client. When a request is received, the request is processed by the <echo-component/> and sent back via the AJAX channel to the client that submitted the request.

RPC Example Client Code

The browser sends information to Mule (using the JavaScript Mule client) when a button is pushed, just as it did before. This time however, a callback method displays the response.

Making an RPC Call - Expecting a response

               
            
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<head>
    <script type="text/javascript" src="mule-resource/js/mule.js"></script> ❶
    <script type="text/javascript">
     
        function rpcCallMuleEcho() { 
            // Create a new object and populate it with the request data
            var data = new Object();
            data.phrase = document.getElementById('phrase').value;
            data.user = document.getElementById('user').value;
            // Send the data to the Mule endpoint and set a callback to handle the response.
            // The "mule" element is provided by the Mule JavaScript client.
            mule.rpc("/services/echo", data, rpcEchoResponse); 
        }
 
        // Display response message data.
        function rpcEchoResponse(message) { 
            document.getElementById("response").innerHTML = "<b>Response:&nbsp;</b>" + message.data + "\n";
        }
    </script>
</head>
 
<body>
    <div>
        Your phrase: <input id="phrase" type="text"/>
        <select id="user">
            <option value="anonymous">Anonymous</option>
            <option value="administrator" selected="true">Administrator</option>
        </select>
        <input id="sendButton" class="button" type="submit" name="Go" value="Send" onclick="rpcCallMuleEcho();"/>
    </div>
    <pre id="response"></pre>
</body>

Note the following changes:

  • Loading the mule.js script ❶ makes the Mule client automatically available via the ‘mule’ variable.

  • The rpcCallMuleEcho() ❷ method gathers some data from the page and submits it to the ‘/services/echo’ channel we configured before.

  • The mule.rpc() ❸ method makes the actual call to Mule. This time, it receives three parameters:

    • The channel name.

    • The data to send.

    • The callback method to be invoked when the response is returned.

  • The rpcEchoResponse() callback method ❹ takes a single parameter, which is the response message, and displays its data on the page.

Configuration Reference

Element Listing

Connector

Allows Mule to expose Mule Services over HTTP using a Jetty HTTP server and Cometd. A single Jetty server is created for each connector instance. One connector can serve many endpoints. Users should rarely need to have more than one Ajax servlet connector.

There are no default values in the following table.

Table 1. Attributes of <connector…​>
Name Description

serverUrl

When using Ajax embedded (not within a servlet container), configure a URL to create an Ajax server hosted in Mule. The URL should be in the form of http://(host):(port)/(path). Note: HTTPS can also be used, but you need to set the TLS information on the connector.
Type: string
Required: no
Default: none

resourceBase

Specifies a local path where files are served from. The local path gets mapped directly to the path on the 'serverUrl'.
Type: string
Required: no
Default: none

disableReplyTo

By default, an asynchronous reply to the inbound endpoint is sent back. This can cause unwanted side effects in some cases, use this attribute to disable.
Type: boolean
Required: no
Default: none

logLevel

0=none, 1=info, 2=debug
Type: integer
Required: no
Default: none

timeout

The server side poll timeout in milliseconds (default 250000). This is how long the server holds a reconnect request before responding.
Type: integer
Required: no
Default: none

interval

The client side poll timeout in milliseconds (default 0). How long a client waits between reconnects
Type: integer
Required: no
Default: none

maxInterval

The max client side poll timeout in milliseconds (default 30000). A client is removed if a connection is not received in this time.
Type: integer
Required: no
Default: none

jsonCommented

If true (default) then the server accepts JSON wrapped in a comment and generates JSON wrapped in a comment. This is a defense against Ajax Hijacking.
Type: boolean
Required: no
Default: true

multiFrameInterval

The client side poll timeout if multiple connections are detected from the same browser (default 1500).
Type: integer
Required: no
Default: none

refsThreshold

The number of message refs at which a single message response is cached instead of being generated for every client delivered to. Optimizes a single message being sent to multiple clients.
Type: integer
Required: no
Default: none

Table 2. Child Elements of <connector…​>
Name Cardinality

client

0..1

key-store

0..1

server

0..1

protocol-handler

0..1

Inbound Endpoint

Allows a Mule service to receive Ajax events over HTTP using a Jetty server. This is different from the equivalent servlet-inbound-endpoint because it uses an embedded servlet container rather that relying on a pre-existing servlet container instance. This endpoint type should not be used if running Mule embedded in a servlet container.

Table 3. Attributes of <inbound-endpoint…​>
Name Type Required Description

channel

string

yes

The Ajax channel to bind the service endpoint to. This channel path is independent context path that your application is deployed to in the servlet container.

No child elements.

Outbound Endpoint

Allows a Mule service to send Ajax events over HTTP using Bayeux. JavaScript clients can register interest in these events using the Mule JavaScript client.

Table 4. Attributes of <outbound-endpoint…​>
Name Description

channel

The Ajax channel to bind the service endpoint to. This channel path is independent context path that your application is deployed to in the servlet container.
Type: string
Required: yes
Default: none

cacheMessages

If set to true, the dispatcher caches messages if there are no clients subscribed to this channel.
Type: boolean
Required: no
Default: none

messageCacheSize

If cache messages is set to true, this value determines the size of the memory cache. The cache automatically expires older items to make room for newer items.
Type: integer
Required: no
Default: none

No child elements.

Maven

The Ajax Transport can be included with the following dependency:


         
      
1
2
3
4
<dependency>
    <groupId>org.mule.transports</groupId>
    <artifactId>mule-transport-ajax</artifactId>
</dependency>

Best Practices

  • Use Ajax outbound endpoints mainly for broadcasting information to several clients simultaneously. For example, broadcasting live news updates to several browsers in real time without reloading the page.

  • It’s recommended to subscribe/unsubscribe callback methods associated with outbound channels on <body> onload/onunload. See example above. Pay special attention to unsubscribing callback methods.

  • When sending information back and forth between clients and servers using Ajax you should consider using JSON. Mule provides a JSON module to handle transformations gracefully.