Reputation: 87
I'm building a webapp with yeoman tools using AngularJS, and am having trouble sending a POST request to a server side script from a controller. Here is the function in my controller code:
$scope.addUser = function() {
$http.post('addUser.php', $scope.user).success(function(response) {
console.log('success');
console.log(response);
$scope.showForm = false;
$scope.infoSubmitted = true;
}).error(function(err){
console.log('failure');
console.log(err);
});
};
The addUser.php file is located in the app/ directory, along with index.html. I am a little confused as to how AngularJS handles routing, as well. I know that I can define routes for GET requests in the app.js file with .when({ ... })
, but I can't see how to handle POST requests and call server side scripts.
This is the .php file I want to connect to:
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
if (empty($_POST['name']))
$errors['name'] = 'Name is required.';
if (empty($_POST['email']))
$errors['email'] = 'Email is required.';
// return a response ===========================================================
// response if there are errors
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
// if there are no errors, return a message
$data['success'] = true;
$data['message'] = 'Success!';
}
// return all our data to an AJAX call
echo json_encode($data);
Upvotes: 0
Views: 1552
Reputation: 71
Try to put addUser.php to the subfolder - /app/server/addUser.php and do
$http.post('server/addUser.php', $scope.user)...
Also php files will not work with default generator-angular. You need generator-angular-php.
Upvotes: 1