Albert Prats
Albert Prats

Reputation: 796

$http - Angular post parameters and get json from PHP

Im new in Angular and even newer using $http. What I'm not able to get is the following_

This is what I got so far:

$http call:

var deferred = $q.defer();
var parametres = $.param({ nomWS: ws, servidor: ip, query: param, idCamping: dadesCamping[0], forceRenew: renew});       

var url = './api/functions.php?function=callWS_JSON'; 

$http({
    method: 'POST',
    url: url,
    data: parametres,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data) {            
    console.log('success');
    deferred.resolve(data);
}); 

What the php who recieves the call is to retrieve a content using the parameters sended via $_POST[] and get the json using:

$fileContents = file_get_contents($url);        
echo $fileContents;

If I set the parameters manually in the PHP script it outputs a valid JSON string, but when I echo it in order to retrive it in my javascript(angular) code i get the following error in the Chrome console:

SyntaxError: Unexpected token &
at Object.parse (native)
at Vb (http://domain/lib/angular/angular.js:14:208)
at e.defaults.transformResponse (http://domain/lib/angular/angular.js:64:454)
at http://domain/lib/angular/angular.js:64:215
at Array.forEach (native)
at r (http://domain/lib/angular/angular.js:7:280)
at pc (http://domain/lib/angular/angular.js:64:197)
at c (http://domain/lib/angular/angular.js:65:400)
at C (http://domain/lib/angular/angular.js:94:187)
at http://domain/lib/angular/angular.js:95:350

If I echo something before the echo of the content I dont get the error and the console outputs the following:

test
{"clientesPresentes": {"cliente":...

(Cutted the output, but the idea is clear)

I asume that the SyntaxError: Unexpected token & is because of the output. And im pretty sure that the problem is about headers and content-type. Tried to find the parameters to perform a post call and get json content as answer but I dind't managed to find out. So any help would be really apreciated.

Thanks in advance

PD: tried to set header('Content-type: application/json'); in my php file but I get the same SyntaxError: Unexpected token & error

Thanks in advance !

Upvotes: 4

Views: 3370

Answers (2)

You probably have unescaped strings in you JSON file.

Upvotes: 0

Jose Faro
Jose Faro

Reputation: 366

where are comming the params?

I use this way.

var $scope.someData = {
   'param1': 12,
   'param2': 33
};

//someData var can also be set inside a form

<input type="text" ng-model="somedata.param1" >

//post and get available
$http.post('url.php' , $scope.someData)
    .success(function(res){
      ;
             })
    .error(function(error){
      ;
    });

and in the php file get the variables this way

$data = file_get_contents("php://input");
echo $data->param1;

Upvotes: 0

Related Questions