Mawg
Mawg

Reputation: 40140

AngularJs AJAX POST to PHP

It's my first time using POST from AngularJs to PHP.

But, Google is my friend - or so I thought.

According to several Google finds, this could should work fine:

AngularJs:

   var data = $.param({
        json: JSON.stringify({
            userName:  $scope.registrationData.userName,
            email:     $scope.registrationData.email,
            password : forge_sha256($scope.registrationData.password)
        })
    });

   var url = HOST + 'api/register.php?debug';       
   console.log('Register at  ' + url);

   $http.post(url, data)

PHP

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

ChromePhp::log('API: JOSON data = ' . $postdata);
ChromePhp::log('API: decoded data = ' . $request);

But, those two ChromePhp::log showed this in the browser console:

%cF:\DropBox\programs\Xampp\htdocs\api\register.php : 17
log.js:137 API: JOSON data = json=%7B%22userName%22%3A%22n%22%2C%22email%22%3A%22e%22%2C%22password%22%3A%22148de9c5a7a44d19e56cd9ae1a554bf67847afb0c58f6e12fa29ac7ddfca9940%22%7D
log.js:81 %cF:\DropBox\programs\Xampp\htdocs\api\register.php : 18
log.js:137 API: decoded data = 

The decoded JSON is empty :-( So, something is going wrong either with my encoding or my decoding.

I am too close to it to see it - who can spot my d'oh ?

Upvotes: 1

Views: 1272

Answers (2)

Ankh
Ankh

Reputation: 5718

If you want to send your data as JSON, it should be simple as:

var data = {
    userName: $scope.registrationData.userName,
    email:    $scope.registrationData.email,
    password: forge_sha256($scope.registrationData.password)
};

...

$http.post(url, data);

You can also check what's being sent from your Angular application by checking the 'network' tab in Chrome's developer tools. That way you can pinpoint if it's a client or server side issue.

Upvotes: 2

Suresh Kamrushi
Suresh Kamrushi

Reputation: 16076

Either you can try like this:

var data = $.param({userName:$scope.registrationData.userName,
                    email:$scope.registrationData.email,
                    password:forge_sha256($scope.registrationData.password)});        
var config = {headers : {'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8;'}} 

$http.post("url/to/ur/file",data,config)
.success(function(response) {
    $scope.data = response;
});

PHP: you can access data like:

$uesrName = $_POST['userName'];
$email = $_POST['email'];
$password = $_POST['password'];

You will get more info:https://docs.angularjs.org/api/ng/service/$http

Upvotes: 1

Related Questions