Geetha Harika
Geetha Harika

Reputation: 55

How to call playframework api with parameters using ajax from jquery without reloading the page?

I want to load an element in my web application without reloading the entire page using play framework, jquery and ajax. I am not able to call the API with parameters from jquery. What are the changes that should be done or additional code that should be written to call the API with parameters without reloading the entire page using jquery, ajax and play framework?

Previously I've got the same problem with javascript but I've resolved it. The same thing I've tried applying for it also but it has not worked.

<script>
$(document).ready(function(){
  $("#button").click(function(){
        $.ajax({url: "@routes.UserController.getUserKeySearch(keySearchForm.get().keySearchText)", success: function(result){
        console.log(result);
    }});
  });
});
</script>


@inputText(keySearchForm("keySearchText"),'_label -> "")
<input type = "button" value = "Click Me" id = "button">

I am getting NoSuchElementException for the above code:

[CompletionException: java.util.NoSuchElementException: No value present]

Upvotes: 1

Views: 147

Answers (1)

Andriy Kuba
Andriy Kuba

Reputation: 8263

The issue is the code is running on the server side:

url: "@routes.UserController.getUserKeySearch(keySearchForm.get().keySearchText)"

So you need to reload the page to get the correct value of the @routes.UserController.getUserKeySearch(keySearchForm.get().keySearchText)

The solution is to use the Javascript Router, check my answer to your previous question: How to pass arguments using java script window.location to a java method in play framework?

As a result, you will have code like

$("#button").click(function(){
  var searchKey = $('#keySearchText').val(); // Selector could be different. 
  var searchUrl = sRoutes.controllers.UserController.getUserKeySearch(searchKey).url;
  $.ajax({url: searchUrl, success: function(result){
    console.log(result);
  }});
});

Upvotes: 2

Related Questions