Angular $http.post doesn't work

3 years ago

emmil
Member | 26
+
0
-

I'm trying to process $http.post request in my presenter, however I'm not able to get the post parameters that are passed using angular $http.post. Here's my code:

<script>

var myData = { 'param1' : 'value' }

$http.post('?do=myMethod', myData).then(function(response) {
  console.log(response)
}, function(error) {
  console.error(error)
})

</script>

And presenter:

<?php

public function handleMyMethod()
{
    // Set post params
    $post = $this->httpRequest->getPost();

    // Try to send the params back
    $this->sendResponse( new Nette\Application\Responses\JsonResponse( $post, "application/json;charset=utf-8" ) );

    $this->terminate();
}

?>

It returns empty array. If I change $post variable to something like array(‘myParam’ ⇒ ‘value’) just to test it out, it returns the array just fine. Therefore the problem is that it doesn't send the post data to the presenter or I'm doing something wrong when processing the post data.

Last edited by emmil (2016-01-27 11:22)

3 years ago

iguana007
Member | 988
+
0
-

And are you sure, that correct URL is being called on backend? Shouldn`t you call:

...
$http.post('?do=myMethod', myData).then(function(response) {
...

3 years ago

emmil
Member | 26
+
0
-

I edited the question, thanks for pointing that out.

3 years ago

iguana007
Member | 988
+
0
-

Did you try to change ContentType?
Try to pass it into JS code this way:

//All browsers but IE
var contentType ="application/x-www-form-urlencoded; charset=utf-8";
//IE content type
if(window.XDomainRequest) {
    contentType = "text/plain";
}
var req = {
 method: 'POST',
 url: '?do=myMethod',
 headers: {
   'Content-Type': contentType
 },
 data: { 'param1' : 'value' }
}

$http(req).then(function(){...}, function(){...});

3 years ago

emmil
Member | 26
+
0
-

Changing the ContentType doesn't make a difference – I still receive an empty array. The solution is this:

<?php

public function handleMyMethod()
{
    // Set post params
    $post = $this->httpRequest->getRawBody();

    $post = json_decode($post);

    // Try to send the params back
    $this->sendResponse( new Nette\Application\Responses\JsonResponse( $post, "application/json;charset=utf-8" ) );

    $this->terminate();
}

?>

Which is basically receiving the data as a string and decodes them into php array which is then send back as a json response. However the main point was to get access to the post data in the presenter (I was sending the response back just to check if the data I posted were received in the presenter correctly), which is what I have now so the problem is solved.