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:


# Javascript routing
GET /javascriptRoutes    controllers.Application.javascriptRoutes

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

routes file contains:


GET  /isEmailExist/:email            controllers.Application.isEmailExist(email: String)

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

The scala version, accessing the body:


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")

Step 4: Create an action translating common routes to JS

The scala version, accessing the body:


def javascriptRoutes = Action { implicit request =>
import routes.javascript._
Routes.javascriptRouter("jsRoutes")                    (routes.javascript.Application.isEmailExist)).as("text/javascript")

Step5: Include javascriptRoutes in main template


<script type="text/javascript" src="@routes.Application.javascriptRoutes"></script>

Step6: Design Your SignUp Form


@(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) {


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

'_label -> "Password",
'_help -> "A password must be at least 6 characters. "

'_label -> "Repeat password",
'_help -> "Please repeat your password again.",
'_error -> signupForm.error("password")


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



Step7: javascript code for making ajax call


<script type="text/javascript">
var successFn = function(data) {
if(data == "true"){
$("#alert-box").append('<div>' + '<a data-dismiss="alert">×</a>  ' +
'<strong>Error!</strong>Email Id Already exist ! '+ '</div>');
$("#alert-box").append('<div>' + '<a data-dismiss="alert">×</a>  ' +
'<strong>Success!</strong>Valid Email Id ! '+ '</div>');
console.debug("Success of Ajax Call");
var errorFn = function(err) {
console.debug("Error of ajax Call");

ajax1 = {
success: successFn,
error: errorFn

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



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:


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
Now if we put a new email id and hit tab, we would see the form with following alert

Entire code can be found here:

About ruchijindal

Software Engineer in Knoldus
This entry was posted in Scala and tagged , , , , , . Bookmark the permalink.

One Response to 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

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s