Poulami
Poulami

Reputation: 61

not receiving data from android in symfony

I have a symfony project and now I am trying to receive the data from android device and access that data via json encoding but the data is not actually received. Instead a layout.html.twig is sent back as the response to android app.

I am using the following code to receive the data in my controller...

    $email = $_POST['email'];
    $response = new Response(json_encode(array('name' => $email)));
    $response->headers->set('Content-Type', 'application/json');

    echo $response;

But the browser says Undefined index: email in /home/external/public_html/src/Apostle/ApiBundle/Controller/DefaultController.php

Where am I going wrong?????

Upvotes: 0

Views: 298

Answers (2)

Pedro Cordeiro
Pedro Cordeiro

Reputation: 2125

There are a lot of things wrong with your code.

  • You should not be reading the $_POST variable. Always use $this->getRequest()->get('email') instead of $_POST['email'].
  • It is generally considered better to instantiate a JsonResponse then to instantiate a Response and set its Content-type to application/json.
  • The reason you are getting the notice with $_POST and a null pointer with $this->getRequest()->get() is because your client (your android device) did not send the email parameter.
  • You should not echo the Response, you should return it.

I hope it helps.

Upvotes: 1

Taytay
Taytay

Reputation: 82

First, about the email error, the request sent to the controller doesn't have the 'email' post parameter.

Then you have to return the response in the symfony controller, not just echo it.

UPDATE:

I think you shouldn't use the $_POST directly in symfony, please use the $this->getRequest()->get() method, or $this->getRequest->request->get() method for specific POST parameters.

Upvotes: 1

Related Questions