So I have successfully gotten AJAX requests to work before but I have always had to use a form, and then at the end of the submit do return false so that it doesn’t refresh the page.
I have also just recently moved my JavaScript into a separate file this has caused my @ commands to fail. Because of this I do not no how to set my URL to my route?
HTML:
<button id="saveAsDefaultButton">Save as default</button>
Playframework Java code:
public static Result saveDefaultPhoneForUser(String handset) {
User currentUser = User.findByName(session("name"));
currentUser.lastControlledHandset = theHandset;
currentUser.save();
return ok();
}
routes:
POST / controllers.Application.saveDefaultPhoneForUser(handset : String)
javascript:
$('#saveAsDefaultButton').click(function(evt) {
$('#errors').hide();
$.ajax({
type : 'POST',
url : "controllers.Application.saveDefaultPhoneForUser",
data : $('#controlledPhone option:selected').text(),
dataType : "text",
success : function(data) {
//setError('Call succedded');
//$('#test1').attr("src", data)
},
error : function(data) {
setError('Make call failed');
}
});
return false;
});
I’m sure there is a way to do this but I am just having no luck finding anything.
For this job you should go with
javascriptRoutesas it generates correct JS paths based on your routes.conf. You’ll find usage sample in Zentask sampleAnyway, for now you can fix your AJAX call by changing the
urltoThis way requires it to place the whole JS in template, which is wrong. It can or even should be moved to separate JS file and to make it possible you need to use javascriptRoutes.
More…
javascriptRoutes are not described yet in official documentation, but here’s step-by-step introduction to it. Although the description looks sophisticated de facto using this way brings a lot of benefits.
1. Create the common routes
First you need to create common routes in
conf/routesfile:Of course, you need to create at least these three actions in
Applicationcontroller:getItem(Long id){ ... }newItem() { ... }updateItem(Long id) { ... }2. Create an action translating common routes to JS
ApplicationcontrollerjavascriptRoutes()In that action you’ll point the existing routes from the
conf/routesfileNote: Don’t set any params in brackets.
3. Create a route for
javascriptRoutesaction and include it in your templateRoute
conf/routesView in
<head>part of/views/main.scala.html4. Use javascriptRoutes where you want
Up from now you can use routes in JS to get the correct path without need to specify the
urlandtype. For an example instead of:you can use simplified version (
myJsRoutesfrom point 2):or
etc…
type: "POST"– JS router will use correct method according toconf/routesruleidof the record (or other params) toGETorPUT(or other methods) usingroutes-likesyntax in pure JSfor route:
JS: