Slim Post method not working with AngularJs Http Request - angularjs

This is my AngularJS controller :
app.controller('emailConfirmCtrl', function ($scope, $http) {
$scope.check_credentials = function () {
var request = $http({
method: 'POST',
url: 'api/slim.php/website/email_verification',
data: {
email: 'email#abc.com'
},
headers : {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8' }
});
/* Check whether the HTTP Request is successful or not. */
request.success(function (data) {
console.log('email sent successfully');
console.log(data);
});
}
});
And in my Slim API I am trying to access data like this:
$app->post("/website/email_verification", function () use ($app, $db) {
$request = $app->request();
$body = json_decode($request->getBody());
// $email_id = $body['email'];
echo $body;
});
But I am getting Error 404, but if I change post method to get then there is no 404 error(i.e url given in AngularJS controller is fine).
How can I access email_id in my SLIM API with post method.

$app->post(
'/login',
function () use ($app) {
$app->response()->header("Content-Type", "application/json");
$post = json_decode($app->request()->getBody());
$postArray = get_object_vars($post);
$login = $postArray['login'];
$pass = $postArray['pass'];

for json you can read raw request body
you will decode the input stream
$body = json_decode(file_get_contents('php://input'));
in your case you can try this
$app->post("/website/email_verification", function () use ($app, $db) {
$body = json_decode(file_get_contents('php://input'));
echo $body;
});

Related

Http Post request is not getting successful in angular js(1.5)

I am working on HTTP post request in angular JS (1.5).
First I pass request data to factory method. Call the Http post request and send the response back to controller. But I always get the below error:
Failed to load resource: the server responded with a status of 404 (Not Found)
Below is my controller code:
app.controller("logicCtrl",['$scope','getDestinationService','getVehicleService','getTokenService','getResultService','$http',
function($scope, getDestinationService,getVehicleService,getTokenService,getResultService,$http){
$scope.getResult = function(){
var resultPromise = getResultService.getFinalResult($scope.request_data);
resultPromise.then(function(result){
$scope.result = result.data;
console.log("result:"+$scope.result);
});
}
});
And this is my factory method:
app.factory("getResultService",['$http','$q',function($http, $q){
var getResultApi = "https://findfalcone.herokuapp.com/find";
var headers = {'Accept' : 'application/json'};
var getFinalResult = function(request_data){
var deferred = $q.defer();
var request_data = JSON.stringify(request_data);
return $http({
url: getResultApi,
method: "POST",
data: request_data,
headers: {'Accept' : 'application/x-www-form-urlencoded'}
}).then(function (response) {
if (typeof response.data === 'object') {
deferred.resolve(response.data);
} else {
deferred.reject(response.data);
}
}).catch(function(response) {
return deferred.reject(response.data);
});
return deferred.promise;
};
return { getFinalResult: getFinalResult };
}]);
Edit: As some people are directly hitting the URL in browser and saying URL is not working. It won't work this way as it is post call, not get call. I tried testing this URL in Postman and it is working absolutely fine.
Here is the screenshot:
In the getFinalResult you are overwriting the Accept header as application/x-www-form-urlencoded where as it should be application/json. You are not using the headers variables declared earlier.
Disclaimer: I wrote the Finding Falcone backend application.

How to return server response via $service.save()

I am new in AngularJS and I have got this problem. I have got defined service citiesService with method addCity:
.service('citiesService', ['$resource', function($resource){
this.addCity = function(city) {
var cityItem = $resource("server/?module=cities&action=add", {}, {save: {method: "POST", isArray:true}});
return cityItem.save({
city: city
});
};
}])
It works fine, the new city was successfully added into DB via the PHP script, but I don't know, how to return server response. Server returning response like:
$output = [];
$output[] = ["success" => "added to database"];
echo json_encode($output);
and then I have got this controller:
.controller('citiesAddCtrl', function($scope, $modalInstance, citiesService) {
// save addCity form (modal)
$scope.saveForm = function() {
if($scope.city.name) {
$scope.a = citiesService.addCity($scope.city);
}
}
})
but I really don't know, how to display server JSON response. When I try something like console.log($scope.a), It shown empty array, but as you can see, the server response is in the right debug menu:
Can you help me to solve this problem please? I read some Stackoverflow topics and tried some edits, which are described here, but nothing works for me.
Since save returns a promise, you could access the response as following (untested):
.controller('citiesAddCtrl', function($scope, $modalInstance, citiesService) {
// save addCity form (modal)
$scope.saveForm = function() {
if($scope.city.name) {
citiesService.addCity($scope.city).$promise.then(function(response) {
$scope.a = response
});
}
}
})
Why don't you use simply $http which has a clear promise structure?
$http({
method: 'POST',
url: "server/?module=cities&action=add",
data: $scope.city
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
See docs at $http

AngularJS Controller function - TypeError: object is not a function

I am creating an email application that makes RESTful calls to Google APIs. I am using AngularJS and Java. I have had some success so far but I am unable to delete an email because I keep getting this error: TypeError: object is not a function.
My Angular knowledge is limited.
In my html I call the function deleteEmail and pass an email id.
Here is the controller:
app.controller('InboxController', function($rootScope, $scope, $cookies,
$location, InboxService) {
$rootScope.loggedIn = true;
$scope.emails = InboxService.getMessages().success(function(jsonData) {
$scope.emails = jsonData;
});
$scope.deleteEmail = function(id) {
$scope.id = {
'id' : id
};
// Parse to JSON
var responseJSON = angular.toJson($scope.id);
// Make call to InboxService
var response = InboxService().del(responseJSON).success(
function(jsonData) {
response = jsonData;
if (response == 'success') {
alert('Message deleted');
} else {
alert('Message not deleted');
}
});
}
});
The method $scope.emails works fine. It is the $scope.deleteEmail that is giving the error.
Here is the service:
app.factory('InboxService', function InboxService($http) {
var exports = {};
// Get a list of all emails
exports.getMessages = function() {
return $http.get('resources/inbox/get').error(function(data) {
console.log('There was an error!', data);
});
};
// Delete an email
exports.del = function(id) {
console.log('id ' + id);
return $http({
method : 'POST',
url : 'resources/inbox/delete',
data : id,
headers : {
'Content-Type' : 'application/json'
}
});
};
return exports;
});
I don't think I am getting as far as the service though. The problem seems to be with the controller.
Console output:
TypeError: object is not a function
at Scope.$scope.deleteEmail (http://localhost:8080/NewProject/js/controllers.js:64:18)
at Parser.functionCall (http://localhost:8080/NewProject/bower_components/angular/angular.js:10903:21)
at ngEventDirectives.(anonymous function).compile.element.on.callback (http://localhost:8080/NewProject/bower_components/angular/angular.js:19259:17)
at Scope.$get.Scope.$eval (http://localhost:8080/NewProject/bower_components/angular/angular.js:12811:28)
at Scope.$get.Scope.$apply (http://localhost:8080/NewProject/bower_components/angular/angular.js:12909:23)
at HTMLButtonElement.<anonymous> (http://localhost:8080/NewProject/bower_components/angular/angular.js:19264:23)
at http://localhost:8080/NewProject/bower_components/angular/angular.js:2853:10
Pls be sure you called deleteEmail(id) from within html with right syntax without $scope
I got it working. I changed the Controller delete method to this:
$scope.delete = function (id) {
InboxService.delete(id).success(function() {
$scope.loadInbox();
});
};
And the Service method to this:
// Delete an email
exports.delete = function(id) {
console.log('id ' + id);
return $http({
method : 'DELETE',
url : 'resources/inbox/delete',
data: id,
headers : {
'Content-Type' : 'application/json'
}
});
}

How can i use Restful in angularjs.I used ngResource but its not working .The js file nt executing if i used ngResource

var app = angular.module('app', ['ngResource']);
app.factory('UserFactory', function ($resource) {
return $resource('/com/vsoft/rest/users', {}, {
query: {
method: 'GET',
params: {},
isArray: false
}
});
});
app.controller('MyCtrl1', ['$scope', 'UserFactory', function ($scope, UserFactory) {
UserFactory.get({}, function (userFactory) {
$scope.firstname = userFactory.firstName;
$scope.lastname = userFactory.lastName;
});
});
}]);
i added above app in my html.But the app and angular-resource.js but my app.js is not exeuting.
If i removed ngResource module and $resource alert is coming.But if i used ngResource im nt getting alert.
Please help in this.If any one knows any Good Example to use Restful services with angularjs .Please Kindly send Url or code.
Please help me.
i called{{firstname}}
in my html but its not coming .
I use a service for handling RESTful messages
app.service('restService', function ($http, $log) {
'use strict';
var self = this;
var BASE_URL = "base/url/";
//First way how to do it
self.httpGet = function (url) {
$log.info("HTTP Get", url);
return postProcess($http({method: 'GET', url: BASE_URL + url}));
};
//Second way how to do it
self.httpPut = function (url, object) {
$log.info("HTTP Put", url);
return postProcess($http.put(BASE_URL + url, object));
};
self.httpPost = function (url, object) {
$log.info("HTTP Post", url);
return postProcess($http.post(BASE_URL + url, object));
};
self.httpDelete = function (url) {
$log.info("HTTP Delete", url);
return postProcess($http.delete(BASE_URL + url));
};
function postProcess(httpPromise) {
return httpPromise.then(function (response) {
if (response.status === 200) {
return response;
}
//Other than 200 is not ok (this is application specific)
failure(response);
}, function (response) {
failure(response);
});
}
/**
* Promise for failure HTTP codes
* #param response the HTTP response
*/
function failure(response) {
//Error handling
}
});
usable as
restService.httpGet("categories").then(function (response) {
categoryData = angular.fromJson(response.data);
//Broadcast an event to tell that the data is ready to be used
$rootScope.$broadcast("categoriesReady");
});

How i can get response from $resource POST request

So looks my request:
angular.module('todoApp').factory('UsersService', ['$resource', 'paramsService', '$q', function($resource, paramsService, $q){
var server = paramsService.serverUrl;
return {
'auth': function(username, password){
var $response = {};
$resource(server + '/api/account/auth', {}, {call: {method: 'POST', headers: {'Content-Type': 'application/json'}}}).call(
{'username': username, 'password': password},
function(data){
console.log(data);
$response = data;
}
);
console.log($response);
return $response;
},
}
}]);
At success function i hava response in data, but variable $response is empty. I know but why it happens, but can't find way to wait response to return it. How can i get response from $resource?
As charliefl commented you need to use the promise object returned from the $resource request to await the completion of the function ($resource is asynchronous).
My PHP code for handling the POST request returned the number of bytes written to the file. I parsed that back from the response using the code below. Since the 'resource' object was not a true array (like 'arguments') I had to loop through possible indices until one returned 'undefined'.
So the bottom line is whatever is in your response body will be returned to you as an array of bytes on the resource object.
$resource(...POST REQUEST...)
.$promise.then(function (resource) {
var bytesSaved = '';
var i = 0;
while (resource[i] !== undefined) {
bytesSaved += resource[i];
i++;
}
$scope.lessonMsg = 'File saved, ' + bytesSaved + ' bytes'
}
function(error) {
$scope.msg = 'An error occurred trying to save the file. ' + error;
}
);
Here is the PHP code generating the POST response:
case "POST":
$params = explode("file/", $_SERVER['REQUEST_URI']);
$filename = '../common/resources/fileContents' . $params[1] . '.json';
$data = file_get_contents("php://input");
$data = json_decode(file_get_contents("php://input"),false);
$fileJson = file_put_contents($filename, json_encode($data));
echo $fileJson;
break;
The file_put_contents() call returns the number of bytes written or false if there was an error.
Hello #falloff please try with below code snippet, I think this will work for you. Also, let me know whether It works or not.
angular.module('todoApp').factory('UsersService', ['$resource', 'paramsService', '$q', function($resource, paramsService, $q){
var server = paramsService.serverUrl;
return {
'auth': function(username, password){
let resource = $resource(server + '/api/account/auth', {}, {
save: {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
},
});
resource.save(
{'username': username, 'password': password}, (response) => {
if (response.length !== 0 && response.length === 0) {
// You will get respose here in 'response'
}
else {
// If response is null
}
deferred.resolve('request successful');
},
(err) => {
// Error
deferred.reject(err);
});
},
}
}]);

Resources