0

I am trying to use the data sent cia the following JQuery POST:

    $.ajax({
        type:  'POST',
        data : JSON.stringify({
            'email' : 'test@example.com',
            'password' : 'mypassword'
        }),
        url:   'http://example/api/login',
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },

        success: function(data){

            //If the response is successful
            if (data.status)
            {
            } else {
            }

        }
    });

In Zendframework / ApiGility I would traditionally do something along these lines to grab the information being sent:

    $email = (string) $this->params()->fromPost('email',false);

Although this is not working with jQuery

Any ideas?

HappyCoder
  • 5,985
  • 6
  • 42
  • 73

2 Answers2

2

You're posting a JSON string rather than a traditional key -> value POST object. This means ZF2 won't be able to pick out the email key because it doesn't know how to parse the request.

You either need to sent the data as a Javascript object:

data : {
    email    : 'test@example.com',
    password : 'mypassword'
},

Or json_decode the request body and get the email from the resulting array e.g. $array['email'].

Ankh
  • 5,478
  • 3
  • 36
  • 40
  • The JSON is because I am posting to ApiGility which only accepts, json, if I otherwsie I get an invalid content type error. I used json decode for this to get at the stdClass object. – HappyCoder May 19 '15 at 15:18
  • I see, that's fair enough. The `json_decode` route seems sensible! – Ankh May 19 '15 at 15:24
0

This is what I did to get to the data:

$request = $this->getRequest()->getContent();

$content =  json_decode($request);
$email = '';
$password = '';

if ($content instanceof \stdClass )
{
     $email = $content->email;
     $password = $content->password;
}
HappyCoder
  • 5,985
  • 6
  • 42
  • 73