1

I have a PHP service at api/add in my application, and you can pass it rq and name via POST. rq tells the service what function to perform, so in my example addCity is defined, and it inserts a city into the database, and name is the name of the city.

So, with that being said, here is my angular code. I'm defining an angular module above with ngRoute.

whereApp.controller('AddCityCtrl', function($scope, $http) {

  $scope.addCity = function() {

    $http({
        method: "POST",
        url: '/api/add/',
        data: { rq:'addCity', name: $scope.name },
        headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).success(function (data, status, headers, config) {
            console.log(data); 
        });

    /*
        $.ajax({
            url: "/api/add/",
            type: "POST",
            data: { rq: 'addCity', name: $scope.name },
            dataType: "json"
        })
        .success(function(data) {
            console.log(data);    
        });
    */
  }
});

Here's the problem. The ajax request (jQuery style that is commented out) works. I'm wanting to use the angular style since, well, it's what I'm using and what I'm trying to learn a little bit more about. The jQuery ajax call gives me back the success message that I have from server-side, and the $http method says that the rq variable is not defined, which I'm accessing via $_POST['rq'].

I've done some research already on Google, but so far have only come up with adding headers: {'Content-Type': 'application/x-www-form-urlencoded'} like this post says.

Can anyone tell me what the difference is between these two ajax calls (or if there is something else I haven't considered)?

Community
  • 1
  • 1
ncf
  • 556
  • 4
  • 16

1 Answers1

2

Since it is json data that is being sent in php you cant get it by simple $_POST you need to do this kind of stuff to get this posted data

$data=file_get_contents('php://input');
$dataobj= json_decode($data);

Here you get data first then decode it from json to normal object

A.B
  • 20,110
  • 3
  • 37
  • 71