Newer Version Available

This content describes an older version of this product. View Latest

Calling a Server-Side Action

Call a server-side controller action from a client-side controller. In the client-side controller, you set a callback, which is called after the server-side action is completed. A server-side action can return any object containing serializable JSON data.

A client-side controller is a JavaScript object in object-literal notation containing name-value pairs. Each name corresponds to a client-side action. Its value is the function code associated with the action.

Let’s say that you want to trigger a server-call from a component. The following component contains a button that’s wired to a client-side controller echo action. SimpleServerSideController contains a method that returns a string passed in from the client-side controller.

1<aura:component controller="SimpleServerSideController">
2    <aura:attribute name="firstName" type="String" default="world"/>
3    <ui:button label="Call server" press="{!c.echo}"/>
4</aura:component>

This client-side controller includes an echo action that executes a serverEcho method on a server-side controller.

Use unique names for client-side and server-side actions in a component. A JavaScript function (client-side action) with the same name as a server-side action (Apex method) can lead to hard-to-debug issues.

Tip

1({
2    "echo" : function(cmp) {
3        // create a one-time use instance of the serverEcho action
4        // in the server-side controller
5        var action = cmp.get("c.serverEcho");
6        action.setParams({ firstName : cmp.get("v.firstName") });
7
8        // Create a callback that is executed after 
9        // the server-side action returns
10        action.setCallback(this, function(response) {
11            var state = response.getState();
12            // This callback doesn’t reference cmp. If it did,
13            // you should run an isValid() check
14            //if (cmp.isValid() && state === "SUCCESS") {
15            if (state === "SUCCESS") {
16                // Alert the user with the value returned 
17                // from the server
18                alert("From server: " + response.getReturnValue());
19
20                // You would typically fire a event here to trigger 
21                // client-side notification that the server-side 
22                // action is complete
23            }
24            //else if (cmp.isValid() && state === "INCOMPLETE") {
25            else if (state === "INCOMPLETE") {
26                // do something
27            }
28            //else if (cmp.isValid() && state === "ERROR") {
29            else if (state === "ERROR") {
30                var errors = response.getError();
31                if (errors) {
32                    if (errors[0] && errors[0].message) {
33                        console.log("Error message: " + 
34                                 errors[0].message);
35                    }
36                } else {
37                    console.log("Unknown error");
38                }
39            }
40        });
41
42        // optionally set storable, abortable, background flag here
43
44        // A client-side action could cause multiple events, 
45        // which could trigger other events and 
46        // other server-side action calls.
47        // $A.enqueueAction adds the server-side action to the queue.
48        $A.enqueueAction(action);
49    }
50})

In the client-side controller, we use the value provider of c to invoke a server-side controller action. We also use the c syntax in markup to invoke a client-side controller action.

The cmp.get("c.serverEcho") call indicates that we’re calling the serverEcho method in the server-side controller. The method name in the server-side controller must match everything after the c. in the client-side call. In this case, that’s serverEcho.

Use action.setParams() to set arguments to be passed to the server-side controller. The following call sets the value of the firstName argument on the server-side controller’s serverEcho method based on the firstName attribute value.

1action.setParams({ firstName : cmp.get("v.firstName") });

action.setCallback() sets a callback action that is invoked after the server-side action returns.

1action.setCallback(this, function(response) { ... });

The server-side action results are available in the response variable, which is the argument of the callback.

response.getState() gets the state of the action returned from the server.

Always add an isValid() check if you reference a component in asynchronous code, such as a callback or a timeout. If you navigate elsewhere in the UI while asynchronous code is executing, the framework unrenders and destroys the component that made the asynchronous request. You can still have a reference to that component, but it is no longer valid. Add an isValid() call to check that the component is still valid before processing the results of the asynchronous request.

Note

response.getReturnValue() gets the value returned from the server. In this example, the callback function alerts the user with the value returned from the server.

$A.enqueueAction(action) adds the server-side controller action to the queue of actions to be executed. All actions that are enqueued will run at the end of the event loop. Rather than sending a separate request for each individual action, the framework processes the event chain and batches the actions in the queue into one request. The actions are asynchronous and have callbacks.

If your action is not executing, make sure that you're not executing code outside the framework's normal rerendering lifecycle. For example, if you use window.setTimeout() in an event handler to execute some logic after a time delay, wrap your code in $A.getCallback(). You don't need to use $A.getCallback() if your code is executed as part of the framework's call stack; for example, your code is handling an event or in the callback for a server-side controller action.

Tip

Action States

The possible action states are:

NEW
The action was created but is not in progress yet
RUNNING
The action is in progress
SUCCESS
The action executed successfully
ERROR
The server returned an error
INCOMPLETE
The server didn't return a response. The server might be down or the client might be offline. The framework guarantees that an action's callback is always invoked as long as the component is valid. If the socket to the server is never successfully opened, or closes abruptly, or any other network error occurs, the XHR resolves and the callback is invoked with state equal to INCOMPLETE.
ABORTED
The action was aborted. This action state is deprecated. A callback for an aborted action is never executed so you can’t do anything to handle this state.