0

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

                jQuery.ajax({
                    url: '/rest/session/token',
                    method: 'GET',
                    success: function (token, status, xhr) {
                        var postData = {}
                        postData= {'name': 'user','pass': 'pass'};
                        jQuery.ajax({
                            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) {
                                console.log(data);
                            }
                        });
                    }
                });

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?

2
  • 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 Jul 14 '16 at 10:16
  • @Clive then what is solution for this case? – Yuseferi Jul 14 '16 at 10:21
4

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'];
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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