CHARAFI Saad CHARAFI Saad - 3 months ago 12
PHP Question

Retrieve data sent from Angular to php program?

Here is my function AngularJS

'use strict';

app
.factory('userProvider', function ($rootScope , $http) {

function logIn(user) {
var url='http://127.0.0.1:100/suitecrm/service/rest.php';

/*$http.post(url,user)
.success(function (response) {
console.log(response);
alert(user['username']); //data is displayed normally here
alert(user['password']); //data is displayed normally here
});
*/

$http({
method: 'POST',
url: 'http://127.0.0.1:100/suitecrm/service/rest.php',
//data: 'username: user['username'] , password: user['password'] }
data: { username: user['username'] , password: user['password']}

}).then(function successCallback(response) {
console.log(response);

}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
}

return {
logIn: logIn
}
});


I want to retrieve my two variable username and password in my file rest.php.
Here is the code where i get username and password

$username =$_POST['username'];
$password =$_POST['password'];


But when i open the console an error is displayed : username & password not defined in rest.php so how can i retrieve data in my file rest.php correctly.

Answer

I think that unless you are submitting via a form method="POST" you need to read/parse the raw input stream.

Try with:

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

You can put this at the start of your PHP script. $request will then be an stdClass object with the data as properties.

$username = $request->username;
$password = $request->password;

Alternatively, if you prefer to work with it as assoc array, use:

$request = json_decode(file_get_contents('php://input'), TRUE);

and access data like:

$username = $request['username'];
$password = $request['password'];