0

SOLVED: The problem was with the second echo in my php script. for some reason it was messing up my stuff. Once I only left the first echo, everything seemed to work perfectly fine.

I am trying to create a simple post request with a JSON object to a PHP script. For some reason I am getting "SyntaxError: Unexpected token {" but I have checked my JSON and it is valid. I am not sure what is going on here. I would appreciate any help.

app.factory('HttpRequestFactory', function($http, $q) {
  var HttpRequestFactory = {
    async: function() {
      var deferred = $q.defer();
      var myData = {"param1":"value1","param2":"value2","param3":"value3"};
      var url = '/test.php';
      $http({
          url:url,
          data : myData,
          method : 'POST'
      })
         .success(function (data, status, headers, config) {
            deferred.resolve(data);
         })
         .error(function(data, status, headers, config){
            deferred.reject("An error occured");
         });
      return deferred.promise;
    }
  };
  return HttpRequestFactory;
});

Here is my PHP code. It turns out that if I comment echo json_encode($_POST); the error is gone.

<?php
header('Content-Type: application/json');
    echo json_encode($_POST);
    $arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
    echo json_encode($arr);
?>
Georgi Angelov
  • 4,338
  • 12
  • 67
  • 96

1 Answers1

0

Have you added header to the post request? See this post: How can I post data as form data instead of a request payload?

$http({
    method: 'POST',
    url: url,
    data: xsrf,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Community
  • 1
  • 1
Keven Wang
  • 1,208
  • 17
  • 28