Chapter 5. JavaScript, Ajax, and Comet
Lift is known for its great Ajax and Comet support, and in this chapter, we’ll explore these.
For an introduction to Lift’s Ajax and Comet features, see Simply Lift, Chapter 9 of Lift in Action (Perrett, 2012, Manning Publications, Co.), or watch Diego Medina’s video presentation.
The source code for this chapter is at https://github.com/LiftCookbook/cookbook_ajax.
Trigger Server-Side Code from a Button
Problem
You want to trigger some server-side code when the user presses a button.
Solution
Use ajaxInvoke:
packagecode.snippetimportnet.liftweb.util.Helpers._importnet.liftweb.http.SHtmlimportnet.liftweb.http.js.{JsCmd,JsCmds}importnet.liftweb.common.LoggableobjectAjaxInvokeextendsLoggable{defcallback():JsCmd={logger.info("The button was pressed")JsCmds.Alert("You clicked it")}defbutton="button [onclick]"#>SHtml.ajaxInvoke(callback)}
In this snippet, we are binding the click event of a button to an ajaxInvoke: when the button is pressed, Lift
arranges for the function you gave ajaxInvoke to be executed.
That function, callback, is just logging a message and returning a JavaScript alert to the browser. The corresponding HTML might include:
<divdata-lift="AjaxInvoke.button"><button>Click Me</button></div>
Discussion
The signature of the function you pass to ajaxInvoke is
Unit => JsCmd, meaning you can trigger a range of behaviours: from
returning Noop if you want nothing to happen, through changing DOM elements, all the way ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access