Reputation: 1046
I want to do a request with JQuery to a application method wich has a String arg, but I have a problem passing the value of the string. In my HTML I have this script:
<script>
var search;
$("#search").keyup(function () {
if($(this).val() != search){
search = $(this).val();
//alert(search);
$.get("@routes.Application.autocomplete("+search+")", function (data) {
//some stuff will be done here
});
return false;
}
}).keyup();
My Application method is like:
public static Result autocomplete(String search) {
System.out.println("Searching for: "+search);
final List<String> response = new ArrayList<String>();
response.add("test1");
response.add("test2");
return ok(Json.toJson(response));
}
What happens is that JQuery is not sending the value of search var but instead sending a string "search".
How can I do the concatenation of the string inside JQuery Get()?
Thanks
Upvotes: 1
Views: 714
Reputation: 2184
Maybe you can use the reverse routing and make your ajax call in this way:
Javascript code:
var ajaxProps = jsRoutes.controllers.Application.subscribe(self.emailSuscriber());
$.ajax({
type: ajaxProps.method,
url: ajaxProps.url,
}).done(function( msg ) {
self.alertMessage(msg);
});
Java server code: controller.Aplication
public static Result subscribe(String email){
/* suscribe code */
}
public static Result javascriptRoutes() {
response().setContentType("text/javascript");
return ok(
Routes.javascriptRouter("jsRoutes",
controllers.routes.javascript.Application.suscribe()));
}
Routes file
GET /subscribe/:email controllers.Application.subscribe(email:String)
GET /public/javascripts/routes controllers.Application.javascriptRoutes()
In your HTML template include:
<script src="@routes.Application.javascriptRoutes"> type="text/javascript"</script>
Upvotes: 1
Reputation: 55798
Yo can not mix server-side variables (ie. @routes.C.a(somevar)
) with typical client-side elements, that's obvious! Isn't it?
Tips:
Make a search
param in the route as an optional one
GET /autocomplete controllers.Application.autocomplete(search: String ?= "")
Use 'almost normal' way of building AJAX queries:
// cut...
$.get("@routes.Application.autocomplete()",
{ search: search },
function (data) {
//some stuff ...
}
);
// cut...
validate the incoming value if it isn't empty
or null
and return badRequest()
(probably in JSON format) in such case.
Upvotes: 1