2

Right so I have a angular function that is sending data to a php file using the http method.The php code I want to process the data and echo it back onto the page to confirm that the php file has processed it. I'm currently getting undefined alerted back to me, surely I should be getting the vaule of email back to me?. Thanks all

I'm following this tutorial https://codeforgeek.com/2014/07/angular-post-request-php/

var request = $http({
 method: "post",
 url: "functions.php",
 data: {
    email: $scope.email,
    pass: $scope.password
},
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
});

//.then occurs once post request has happened
//success callback
request.success(function (response) {
  alert(response.data);
},

//error callback
function errorCallback(response) {
  // $scope.message = "Sorry, something went wrong";
  alert('error');
});

My php code...

//receive data from AJAX request and decode
$postdata = file_get_contents("php://input");
$request = json_decode($postdata);

@$email = $request->email;
@$pass = $request->pass;

echo $email; //this will go back under "data" of angular call.

1 Answer 1

1

From the documentation:

The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

Your code should look like this:

request.then(
    function( response ) {
        var data = response.data;
        console.log( data );
    },
    function( response ) {
        alert('error');
    }
);

Now, you need to encode the response from the server in a JSON format, so replace echo $email; with:

echo json_encode( array(
    'email' => $email
) );

And you can access the email property from the angularjs $http.success promise callback function (it's the first function inside the then closure) by response.data.email

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks appreciate your help :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.