Soccertrash
Soccertrash

Reputation: 1901

Ajax Form Submission Play Framework 2.0

I've just started using the Play 2.0 Framwork. I wonder what is the best way to do ajax-based form submission. Currently my pages contains a form and a list below, where the new entries (of the form) should appear. I'd like to do the submission by ajax and also the list update.

But my first question is how to submit the form via ajax and use the form binding and the validation of the Controllers. Is that possible? What is the correct way to do this?

Thanks,

Upvotes: 3

Views: 3828

Answers (2)

Wirus
Wirus

Reputation: 1190

IMHO you could use play's JavaScript Routing functionality, js validation (e.g. jquery validator plugin) and server side validation. First declare case class that will serve as a domain object

case class SimpleUser( name: String, email: String )

then create controller with form and function:

object Users extends Controller{
    //validation 1 goes here
    val userForm = Form(
        mapping(
            "name" -> text,
            "email" -> email
        )(SimpleUser.apply)(SimpleUser.unapply)
    )

    def save = Action { implicit request =>
        userForm.bindFromRequest().fold(
            formWithErrors => {
                BadRequest( "uuuups" ) 
            },
            user => {
                //validation 2 goes here
                Ok( "ok" )
            }
        )
    }
}

Once you have this, you add entries to routes file

POST    /users/save controllers.Users.save
GET     /jsroutes   controllers.Application.javascriptRoutes

and in Application controller

def javascriptRoutes = Action { implicit request =>
    import routes.javascript._
    Ok(
        Routes.javascriptRouter("jsRoutes")(
            Users.save
    ) ).as("text/javascript")
}

And now the JavaScript part

(...)
save: function(){
    jsRoutes.controllers.Users.save().ajax( {
        data: jQuery( 'form' ).serialize(),
        success: function( data ){
            //refresh users' list
        },
        error: function( data ){
            console.log( data.responseText );
        }
    });
}

It's just simple example (and I didn't compile it), but shows the idea.

Upvotes: 6

biesior
biesior

Reputation: 55798

The fastest way is jQuery. Just need to serialize your form and send it with common jQuery.ajax. In response your method should sent a JSON data containing ie. new items and other stuff like custom status etc.

Upvotes: 4

Related Questions