4

I am making the following AJAX request:

$.post('/route', {
    arg1 : 'foo',
    arg2 : 'bar'
});

Through the route:

POST   /route    controllers.Test.readPost()

How do I access these POST variables in the method of my controller?

public static Result readPost() {
    return TODO; // read post variables
}

I cannot find a simple way of doing this in the documentation. It only states how to get values from JSON requests.

biesior
  • 55,576
  • 10
  • 125
  • 182
Jivings
  • 22,834
  • 6
  • 60
  • 101

2 Answers2

9

Use DynamicForm

public static Result getValues(){
    DynamicForm requestData = form().bindFromRequest();

    String name = requestData.get("name");
    String desg = requestData.get("desg");
    // etc

    return ok("You sent: " + name + ", " + desg);
}

There is also other possibility to construct AJAX query and pass arguments via javascriptRoutes: https://stackoverflow.com/a/11133586/1066240

Of course it will pass the params via URL so it's not suitable for every value, but in many places it will be goot enough for sending POST requests with AJAX. Of course javascriptRoutes create the request with type set in routes file.

BTW: it was better if you wrote which version you are using.

Community
  • 1
  • 1
biesior
  • 55,576
  • 10
  • 125
  • 182
  • Worked like a charm. Is this documented? – Jivings Jun 25 '12 at 20:15
  • DynamicForm is documented in the API http://www.playframework.org/documentation/api/2.0.1/java/index.html?play/data/package-summary.html , as far as I know, there's no official doc for javascriptRoutes yet – biesior Jun 25 '12 at 20:22
-2

you can use GET with an ajaxRequest. more information can be found here http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml

var mygetrequest=new ajaxRequest()
mygetrequest.onreadystatechange=function(){
 if (mygetrequest.readyState==4){
  if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
   document.getElementById("result").innerHTML=mygetrequest.responseText
  }
  else{
   alert("An error has occured making the request")
  }
 }
}
var namevalue=encodeURIComponent(document.getElementById("name").value)
var agevalue=encodeURIComponent(document.getElementById("age").value)
mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
mygetrequest.send(null)
Eric Robinson
  • 2,025
  • 14
  • 22
  • This is completely unrelated to the question. I'm asking about the `play framework`, and POST not GET. – Jivings Jun 25 '12 at 14:35