Jivings
Jivings

Reputation: 23262

How do I access POST variables in my controller?

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.

Upvotes: 4

Views: 1858

Answers (2)

biesior
biesior

Reputation: 55798

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.

Upvotes: 9

Eric Robinson
Eric Robinson

Reputation: 2095

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)

Upvotes: -2

Related Questions