In this tutorial we will discuss about the following topics of AJAX calling in Play Framework 2.3.4:
- Embedded router
- Router resource
- jQuery Ajax
- Success/Error handler for each router
- Single Success/Error handler for all routers
∗ Embedded router
An embedded router can be generated using the
Follow the following steps to generate embedded router in the your application:
Step 1: Update and Add new action called ajaxCall in your Application.scala file.
Step 2: Add the above action entry in conf/routes file.
GET /ajax-call controllers.Application.ajaxCall
Step 3: Update index.scala.html with following code.
(implicit req: RequestHeader) to the end of your parameter declarations.
Step 6: Run the application from the console
saurabh@knoldus:~/projects/knoldus/ajax-with-play$ activator [info] Loading project definition from /home/saurabh/projects/knoldus/ajax-with-play/project [info] Set current project to ajax-with-play (in build file:/home/saurabh/projects/knoldus/ajax-with-play/) [ajax-with-play] $ run --- (Running the application from SBT, auto-reloading is enabled) --- [info] play - Listening for HTTP on /0:0:0:0:0:0:0:0:9000 (Server started, use Ctrl+D to stop and go back to the console...)
Step 7: Open the browser the hit the URL: http://localhost:9000/
Source code from the browser
∗ Router resource
A router resource can be generated by creating an action that invokes the router generator. It has a similar syntax to embedding the router in a template. We can generate router resource with the help of following steps:
Step 2: Add the following code it conf/routes file
Step 3: Now we can include it as a resource in our templates views/main.scala.html:
∗ jQuery Ajax
Using jQuery as an example, making a call is as simple as:
To know more about jQuery ajax: here
∗ Success/Error handler for each router
Here we can define callback function for each router.
∗ Single Success/Error handler for all routers
To explore more check the Github code: here