最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Cannot POST data to server through angularjs's $http module - Stack Overflow

programmeradmin1浏览0评论

I am coding using angular ajax. The client side code is:

$http({
    method: 'POST',
    url: '----/test.php',
    data: ({'txtDeviceID': 12345678}),
    headers: {
        'Content-type': 'application/text'
    }
}).then(function successCallback(response) {
    console.log(response)
}, function errorCallback(response) {
    console.log(response)
});

The server side code is:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With,Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
echo $_POST['txtDeviceID'];

Why can't I get the texDeviceId? Thank you for your time!

I am coding using angular ajax. The client side code is:

$http({
    method: 'POST',
    url: '----/test.php',
    data: ({'txtDeviceID': 12345678}),
    headers: {
        'Content-type': 'application/text'
    }
}).then(function successCallback(response) {
    console.log(response)
}, function errorCallback(response) {
    console.log(response)
});

The server side code is:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With,Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');
echo $_POST['txtDeviceID'];

Why can't I get the texDeviceId? Thank you for your time!

Share Improve this question edited Jun 24, 2016 at 13:30 miquelarranz 89411 silver badges26 bronze badges asked Jun 24, 2016 at 12:12 DebojyotiDebojyoti 1691 silver badge14 bronze badges 7
  • try data: {'txtDeviceID':12345678} (i.e. without the brackets) and 'Content-type': 'application/json' – ADyson Commented Jun 24, 2016 at 12:14
  • You might wanna send the data back using json_encode – Michael Doye Commented Jun 24, 2016 at 12:14
  • @ADyson i did it still showing error – Debojyoti Commented Jun 24, 2016 at 12:23
  • @Debojyoti what error do you get? – gevorg Commented Jun 24, 2016 at 12:23
  • @gevorg no value is being sent through the server – Debojyoti Commented Jun 24, 2016 at 12:26
 |  Show 2 more ments

5 Answers 5

Reset to default 2

Your problem

Your problem is, because you send JSON data to PHP file, but PHP expects it to be in form param format:

  • your client code sends {'txtDeviceID': 12345678}
  • but server code expects txtDeviceID=12345678

To solve this you have two options, changing your client code to send data in form param format or changing your server code to expect data in JSON format.

changing your your client code

Look for response.data and change request's content-type to application/x-www-form-urlencoded, additionally you should transform your data to form format using $httpParamSerializer.

$http({
    method: 'POST',
    url: '----/test.php',       
    data: $httpParamSerializer({ 'txtDeviceID': 12345678 }),  
    // or data: "txtDeviceID=12345678",
    headers: {
        'Content-type': 'application/x-www-form-urlencoded'
    }
}).then(function successCallback(response) {
    console.log(response.data)
}, function errorCallback(response) {
    console.log(response)
});

For more info read $http docs

The response object has these properties:

  • data – {string|Object} – The response body transformed with the transform functions.
  • status – {number} – HTTP status code of the response.
  • headers – {function([headerName])} – Header getter function.
  • config – {Object} – The configuration object that was used to generate the request.
  • statusText – {string} – HTTP status text of the response.

or changing your server code.

To get raw submitted data you need to use file_get_contents('php://input')

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With,Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');

$_POST = json_decode(file_get_contents('php://input'), true);
echo $_POST['txtDeviceID'];

set 'Content-type': 'application/json'

try something like this

$http({
    method: 'POST',
    url: '----/test.php',
    data: {"txtDeviceID":12345678},
    headers: {
    'Content-type': 'application/json'
}
  }).then(function (response) {
    console.log(response)
    }, function (response) {
      console.log(response)
    });

modify your php file like this

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: Origin, X-Requested-With,Content-Type, Accept");
header('Access-Control-Allow-Methods: GET, POST, PUT');


$jsonstring = file_get_contents ( 'php://input' );
$arr = json_decode($jsonstring,true);
echo $arr["txtDeviceID"];

In your PHP, change echo $_POST['txtDeviceID']; to echo json_encode($_POST['txtDeviceID']);

and in your controller Make sure that data is on object.

$http({
    method: 'POST',
    url: '----/test.php',
    data: {'txtDeviceID':12345678}
  }).then(function successCallback(response) {
    // look specifically for "txtDeviceID"
    console.log(response.data.txtDeviceID)
    }, function errorCallback(error) {
      console.log(error)
    });

Use $http interceptor like the one below, it work for me

(function(){
  angular.module('xxxxxxx').factory('sessionInjector', function() {  
      var sessionInjector = {
          request: function(config) {

              config.headers['Authorization'] = "Bearer " + sessionStorage.getItem('token');

              if(config.method == 'POST') {
                if(config.data) {
                  config.data = $.param(config.data); //jQuery magic but php likes
                }
              }

              return config;
          },
          response: function(res) {
              console.log(res);
                return res;
          }
      };
      return sessionInjector;
  });
}());
发布评论

评论列表(0)

  1. 暂无评论