Go to page content

Calling Zotonic from Javascript

There are three main ways to call Zotonic from Javascript: wired events, notifications and API methods.

Why

JavaScript is the lingua franca of web scripting.  Having a mechanism of directly integrating Zotonic backend calls into a flow with JQuery has great potential.  This guide provides some pointers on where and how you would achieve this integration.

Assumptions

Readers are assumed to be comfortable both in developing Zotonic templates and in writing Erlang code.

How

You can use three ways to call Zotonic from JavaScript:

  1. Use {% wire %} to defined a named action and trigger it from js with z_event("myname", { foo: bar, ... }). 'foo' and other arguments will become query args (access with z_context:get_q/2 and friends).

    {% wire name="test" action={growl text="Hello World"} %} 

    And then in some JS function:

    z_event("test"); 

    or

    z_event("test", { foo: bar }); 

    Of course, you can also wire postback actions.

  2. Trigger a notification in Zotonic with the z_notify function:

    z_notify("mymessage"); 

    or

    z_notify("mymessage", {foo: bar, lazy: "fox"}); 

    This will trigger a call to:

    z_notifier:first(#postback_notify{message="mymessage"}, Context) 

    Which you can handle in any zotonic module by defining:

    export([ observe_postback_notify/2 ]). 
    observe_postback_notify(#postback_notify{message="mymessage"}, Context) -> 
         z_render:growl("Hello World", Context); 
    observe_postback_notify(_, _Context) -> 
         undefined. 

    All extra arguments are available via the z_context:get_q/2 function (and friends).

  3. Or use API methods and perform callbacks using standard jQuery posts.

The first two are preferred, as they integrate nicely with the notification and action systems. The API is more targeted to other applications interfacing to Zotonic.

Troubleshooting

There are no troubleshooting steps available for this guide.  Please provide any you have learned in the comments below or on the Zotonic Users Group.

This page is part of the Zotonic documentation, which is licensed under the Apache License 2.0.