Play Framework 2.0: Ajax Calling Using Javascript Routing in Scala

Continuing our series on Play Framework, in this blog we’ll learn How to make Ajax call in play using jsRoutes.We have already covered design forms in Play2.0 using Scala and Mongodb in the past.

Play2.0 introduces a powerful feature JavascriptRouter which helps us in making Ajax call.The play router is able to generate JavaScript code to handle routing from JavaScript running client side back to your application. This aids in re-factoring your application, if you change the structure of your URL s or parameter names,your JavaScript gets automatically updated to use that new structure.

There are two ways to generate a JavaScript router, one is to embed the router in the HTML page using template which is define in  views.html.helper package directives, the other is to generate JavaScript resources in an action.

In the following example I am going to use Router resource .A router resource can be generated by creating an action that invokes the router generator.

I am assuming that you have knowledge about design forms in play and  know a little about   Play Templating ,Scala, JavaScript and how play 2.0 works.

Lets consider an example of simply Sign Up mechanism for a User where we want to check whether a user already registered with a given email id or not at the time of registration.We’ll display a alert with validation message on blur of email text-box.

Step 1:Create a route for javascriptRoutes

routes file contains:

conf/routes

[sourcecode language=”scala” wraplines=”false” collapse=”false”]
# Javascript routing
GET /javascriptRoutes    controllers.Application.javascriptRoutes
[/sourcecode]

Step 2:Create the route to check for a email id

routes file contains:

conf/routes

[sourcecode language=”scala” wraplines=”false” collapse=”false”]
GET  /isEmailExist/:email            controllers.Application.isEmailExist(email: String)
[/sourcecode]

Step 3: Create action to check for the existence of an email id

The scala version, accessing the body:

app/controllers/Application.scala

[sourcecode language=”scala” wraplines=”false” collapse=”false”]</pre>
def isEmailExist(email: String) = Action { implicit request =>

//replace this code with your business logic(or model)
to check whether the given email already exist or not
User.findUserByEmail(email).isEmpty match {
case true => Ok("false")
case false => Ok("true")
}
}
<pre>[/sourcecode]

Step 4: Create an action translating common routes to JS

The scala version, accessing the body:

app/controllers/Application.scala

[sourcecode language=”scala” wraplines=”false” collapse=”false”]
def javascriptRoutes = Action { implicit request =>
import routes.javascript._
Ok(
Routes.javascriptRouter("jsRoutes")                    (routes.javascript.Application.isEmailExist)).as("text/javascript")
}
[/sourcecode]

Step5: Include javascriptRoutes in main template

app/views.main.scala.html

[sourcecode language=”scala” wraplines=”false” collapse=”false”]
<script type="text/javascript" src="@routes.Application.javascriptRoutes"></script>
[/sourcecode]

Step6: Design Your SignUp Form

app/views/signUpForm.scala.html

[sourcecode language=”scala” wraplines=”false” collapse=”false”]
@(signupForm: Form[UserSignUpForm],message:String)

@import helper._
@import helper.twitterBootstrap._

@title = {
Sign Up Form in Play2.0
}

@main(title) {

<div id="alert-box">@*Update This Div My Making Ajax Call*@</div>

@helper.form(action = routes.Application.createUser) {

<fieldset>
<legend>@message</legend>

@inputText(
signupForm("email"), ‘_label -> "Email",’onBlur->"isEmailExist()", @*to make ajax call on blur *@
‘_help -> "Enter a valid email address."
)

@inputPassword(
signupForm("password.main"),
‘_label -> "Password",
‘_help -> "A password must be at least 6 characters. "
)

@inputPassword(
signupForm("password.confirm"),
‘_label -> "Repeat password",
‘_help -> "Please repeat your password again.",
‘_error -> signupForm.error("password")
)

</fieldset>

<div>
<input type="submit" value="Sign Up" >
</div>

}

}
[/sourcecode]

Step7: javascript code for making ajax call

app/views/signUpForm.scala.html

[sourcecode language=”scala” wraplines=”false” collapse=”false”]
<script type="text/javascript">
var successFn = function(data) {
if(data == "true"){
$(‘#alert-box’).html(”);
$("#alert-box").append(‘<div>’ + ‘<a data-dismiss="alert">×</a>  ‘ +
‘<strong>Error!</strong>Email Id Already exist ! ‘+ ‘</div>’);
}
else{
$(‘#alert-box’).html(”);
$("#alert-box").append(‘<div>’ + ‘<a data-dismiss="alert">×</a>  ‘ +
‘<strong>Success!</strong>Valid Email Id ! ‘+ ‘</div>’);
}
console.debug("Success of Ajax Call");
console.debug(data);
};
var errorFn = function(err) {
console.debug("Error of ajax Call");
console.debug(err);
}

ajax1 = {
success: successFn,
error: errorFn
}

function isEmailExist() {
var idToGet = $("#email").val();

jsRoutes.controllers.Application.isEmailExist(idToGet)
.ajax(ajax1);

}
</script>
[/sourcecode]

So from the above mentioned 7 steps we learn, how to make Ajax calling using jsRoutes in Play Templating
Suppose we execute the above code by using the command play run .
We would get the form as you see below:

Selection_032

Now lets try to put a existing email id ,As soon as we put a existing email
and hit tab(on blur), we would see the following form with validation alert
Selection_033
Now if we put a new email id and hit tab, we would see the form with following alert
Selection_034

Entire code can be found here: https://github.com/knoldus/FormDemoInPlay

1 thought on “Play Framework 2.0: Ajax Calling Using Javascript Routing in Scala

  1. Awesome tutorial. Do you have an example about populating Play fields (@inputText) from Ajax request? Kind of, I click on a button, do a request getting something and populating my fields in form. Do you?

Leave a Reply

%d bloggers like this: