Skip to content

Instantly share code, notes, and snippets.

@sofoklis
Created February 3, 2012 15:05
Show Gist options
  • Save sofoklis/1730594 to your computer and use it in GitHub Desktop.
Save sofoklis/1730594 to your computer and use it in GitHub Desktop.
lift ajax basics
import net.liftweb.http._
import S._
import js._
import JsCmds._
import JE._
import net.liftweb.util._
import Helpers._
import scala.xml.Text
class AjaxCall {
/**
* Create a javascript command to calculate the value i want to send to the callback function
* here i am just getting the value from the text area.
*/
lazy val calculateValueToSendToServerJsCmd = JsRaw("""$("#ajax_question").val()""")
/**
* Create the ajax call, you get back a tuple, first the key and then the js
* expression to call it from the client site.
*/
lazy val aCall : (String, net.liftweb.http.js.JsExp) =
SHtml.ajaxCall(calculateValueToSendToServerJsCmd, callback)
/**
* You can get the first value of the tuple like so, simply the randomly generated key
*/
lazy val id : String = aCall._1
/**
* Here is the call to the ajax function you have created, it is created to
* call the callback function bellow with whatever we typed in the
* text area as an argument. Remember that its bound to this exact object, so every
* time you refresh your page you will get a different text in the end, because a new
* object will be created, but just pressing the button will give you the same from ... text
* You can think of this as your "url"
*/
lazy val clientCall = aCall._2.toJsCmd
/**
* A callback function, here you can run your logic and return anything you want as a JsCmd
* that will be executed on the client side. Essentially the return value of this function
* is jQuery.ajax "success" function
*/
def callback(value : String) : net.liftweb.http.js.JsCmd = {
println(value)
// Simply a pop up an alert with the message received on the server and the
// id of the object that handled the ajax request, you can see this changing every
// time you refresh the page.
Alert(value + " received on the server from " + this.toString)
}
/**
* Simple CssSel to add the javascript i wanted on the client side, i decided to
* make the more verbose way of doing thing so the example is more clear, and
* you can simply modify to run anywhere. The code create a jQueryUI button
* with a click action to run the lift ajax call
*/
def sample : CssSel =
"#script" #> Script(JsRaw("""
$(function() {
$( '#button' ).button().click(function()
{
""" + clientCall + """
});
})
"""))
/**
* Alternatively you can add the call to the button with the onclick event
* from the, not used now. You get this from reading the lift group a lot.
*/
def alternative : CssSel = "#button [onclick]" #> Text(aCall._2.toJsCmd)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment