2

my angularjs $http

userId = '1';

$http({
url: "php/loadTab.php",
method: "POST",
data: userId
}).success(function(data, status, headers, config) {
    console.log(data);
}).error(function(data, status, headers, config) {
});

heck, POST doesn't send the data to my php. I do echo $_POST['userId'] it returned undefined index. I also tried data:'userId':'1'

5
  • 2
    Did you try data:{'userId':'1'} ? Commented Apr 22, 2014 at 11:56
  • @SubirKumarSao yes, not working Commented Apr 22, 2014 at 12:04
  • $http sends data as JSON, that's why there is nothing in PHP's $_POST. There numerous similar questions here on SO. Commented Apr 22, 2014 at 12:05
  • possible duplicate of AngularJS | How to Send the Data of Json to database in Codeigniter Commented Apr 22, 2014 at 12:31
  • I know it's got a CodeIgniter tag but it's irrelevant. Commented Apr 22, 2014 at 12:32

1 Answer 1

2

Angular sends the data as JSON, not form encoded key/value pairs so you can set data to an object. You almost have it on your second try but you need to include the curly braces, which define an object:

data: { 'userId' : userId }

Now, on the PHP side you need to access the raw POST data to decode the JSON like so:

$data = json_decode(file_get_contents('php://input'));
echo $data->userId;
Sign up to request clarification or add additional context in comments.

5 Comments

I seem still don't pass the data. still got the same error.
Did you try it and it worked ? Because last time I checked, $http would by default send data as JSON, so nothing would be found in PHP's $_POST variable.
@ExpertSystem so? just now I use params:{'userId','1'} and it worked but it's $_GET; I need $_POST
See my comment above.
@user3522457 see updated answer. ExpertSystem is correct about the JSON, so you need to access it in a different way on the PHP side.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.