user1397499
user1397499

Reputation: 21

Call java function from javascript in play framework

I am doing a project using play framework.

After clicking some link for example "show" then for example car.show(55) is being called and in car.show some db query is being performed. then list operation is being done.

What I am trying to do is, call removegivencar function from java script file.

I mean,

when all cars are listed in html file. I will call a js function with the id of that car.

For example: Remove My Car

and I would like to call car.removegivencar function in js instead of html

Because I have an id of the car. I should do @{car.removMyOwremovegivencar(mycar.id)} operation...

I tried

function removeMyCar(id)
{
window.location="@{car.removMyOwremovegivencar(id)}";
}

or window.location="@{car.removMyOwremovegivencar(" + id + ")"

etc. but could not do it :((( please drive me on this issue...

Upvotes: 2

Views: 7704

Answers (3)

Market
Market

Reputation: 450

This post could help you: javaScriptRouter

In this example you can take the url with this code

var url = jsRoutes.controllers.Application.plus(num1,num2).url;

Upvotes: 1

marteljn
marteljn

Reputation: 6516

The short answer is you cannot directly call a java method/function from javascript. You could however make an ajax request to a server-side resource that will call your function. The results of the ajax request would be the results of your function in whatever format you so choose.

Upvotes: 2

wassertim
wassertim

Reputation: 3136

If it is written properly then it should work. But in fact it is a bad example for deleting entities from your DB. That's because of the GET request you are trying to use. It is not only logical to use GET for deleting, but it also might be dangerous for your application in some cases. But if you use it this way check the following:

You route file should contain something like that:

GET    /car/remove/{id}         car.removMyOwremovegivencar()

Also make sure you pass id param to your view from which you are trying to call you js code. I don't see any other reasons making this code not working.

But consider better way:

It is to make this action POST or DELETE and make an AJAX call on it:

route:

DELETE   /car/{id}         car.removMyOwremovegivencar()

and your JS (with jQuery):

function removeMyCar(id)
{
   $.ajax({
    type: "DELETE",
    url: "@{car.removMyOwremovegivencar()}",
    data: {
      id:id
    }
   });
}

Upvotes: 7

Related Questions