1

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!

7
  • try data: {'txtDeviceID':12345678} (i.e. without the brackets) and 'Content-type': 'application/json' Commented Jun 24, 2016 at 12:14
  • You might wanna send the data back using json_encode Commented Jun 24, 2016 at 12:14
  • @ADyson i did it still showing error Commented Jun 24, 2016 at 12:23
  • @Debojyoti what error do you get? Commented Jun 24, 2016 at 12:23
  • @gevorg no value is being sent through the server Commented Jun 24, 2016 at 12:26

5 Answers 5

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'];
Sign up to request clarification or add additional context in comments.

4 Comments

But i can see in console.log(response) that the data property has empty value
@Debojyoti got it, your problem is in headers, because you don't set proper header for content type, use this 'Content-type': 'application/x-www-form-urlencoded'
@Debojyoti additionally you need to convert submitted data to form format using $httpParamSerializer.
@Debojyoti there is an alternative to that where you can just change your server code.
2

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

Comments

2

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"];

Comments

2

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)
    });

Comments

1

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;
  });
}());

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.