Debojyoti Debojyoti - 5 months ago 28
AngularJS Question

Cannot POST data to server through angularjs's $http module

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!

Answer

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'];
Comments