I want to do some tasks with ajax in drupal, in client side I passed data with

                    url: '/rest/session/token',
                    method: 'GET',
                    success: function (token, status, xhr) {
                        var postData = {}
                        postData= {'name': 'user','pass': 'pass'};
                            url: "/mylogin",
                            method: "POST",
                            data: postData,
                            dataType: "json",
                            headers: {"Accept": "application/json", "X-CSRF-Token": token, "Content-Type": "application/json"},
                            success: function (data, status, xhr) {

and ccording How to get $_POST parameters in my controller I try to catch posted data with

public function login(){
    //return new JsonResponse( \Drupal::request()->request->all()); // form param);
    return new JsonResponse( \Drupal::request()->request->get('name')); // form param);

I reutrn empty, ( JsonResponse work correctly, I test it with example data ).

what is the problem and why I can't get Posted data in my controller's method?

  • 1
    The request/query get methods get raw data I think, i.e. there's no special handling to convert an incoming json string to key/value pairs. So there won't be a $_POST['name'], just raw post data that contains a JSON string.
    – Clive
    Commented Jul 14, 2016 at 10:16
  • @Clive then what is solution for this case?
    – Yuseferi
    Commented Jul 14, 2016 at 10:21

1 Answer 1


If you're POSTing a JSON string, it won't be available as key/value pairs in Symfony's request object.

You could parse it yourself:

$json_string = \Drupal::request()->getContent();
$decoded = \Drupal\Component\Serialization\Json::decode($json_string);
$name = $decoded['name'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.