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);
});
},
}
}]);
Related
Hi this below is my code from angularjs
The first part of the code shows exactly how I make the request to php which returns me data when there is code with an error when there is a problem.
When it returns me an error code, for example 401, the frontend explodes with an error and everything breaks.
As far as I understand, I have to use an interceptor so that I can catch the error number and not make an error.
I can't do this interception.
app.js
app.factory('httpRequester', function ($http, $route) {
var promise;
var myService = {
async: function (myData) {
//Create my obj for request
var req = {
method: myData.Method,
url: 'https://**********/' + url,
headers: {
'X-API-KEY': '**************',
'KEY': myData.Authentication.AccessToken
},
data: myData
};
promise = $http(req).then(function (response) {
if (response.data === 'permission denied') {
window.location.href = '#/';
} else {
return response;
}
});
return promise;
}
};
return myService;
});
//set interceptor in app.js
var interceptorApp = angular.module('interceptorApp', []);
interceptorApp.config(function($httpProvider) {
$httpProvider.interceptors.push('genericInterceptor');
});
Please help me with my problem, how to set interceptor work.
//Function for set error and success after request
var testInterceptor = function ($q)
{
return {
request: function (config)
{
//console.log('request started...');
},
requestError: function (rejection)
{
console.log(rejection);
// Contains the data about the error on the request and return the promise rejection.
return $q.reject(rejection);
},
response: function (result)
{
// console.log('data for ' + result.data.name + ' received');
//If some manipulation of result is required before assigning to scope.
result["testKey"] = 'testValue';
console.log('request completed');
return result;
},
responseError: function (response)
{
// console.log('response error started...');
//Check different response status and do the necessary actions 400, 401, 403,401, or 500 eror
return $q.reject(response);
}
}
}
I am Passing my user information http angularjs. backend code is PHP
As I am the beginner I am searching lot for this Issue. and tried a lot methods since 2 days but I couldn't find the reason, and how to fix it?. it may be simple but I couldn't find.
1.I am posting my http post request in angularJS I have been debugged the value which I will send is
Debugging value are as follow:
serializedParams:"send_id=78&send_name=Douby&send_phone=4528&send_status=Due"
url: "insert.php?send_id=78&send_name=Douby&send_phone=4528&send_status=Due"
result: undefined
I think the url is correct. but the result is undefined
var app = angular.module("myapp", []);
app.controller("booking", function($scope, $http) {
$scope.paidops = ["Paid", "Due"];
$scope.value = "ADD";
$scope.insertvalues = function() {
alert($scope.id + ' , ' +
$scope.name + ' ,' + $scope.phone +
' , ' + $scope.status);
alert($scope.name);
var Indata = {
'send_id': $scope.id,
'send_name': $scope.name,
'send_phone': $scope.phone,
'send_status': $scope.status
};
$http({
method: 'POST',
url: 'insert.php',
params: Indata,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(response) {
alert(JSON.stringify(response));
}, function(response) {
alert(response);
});
}
});
In PHP I am getting data like this way:
$connect = mysqli_connect("localhost:3307", "root", "", "ticket_booking");
if($connect === false){
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$data = json_decode(file_get_contents("php://input"),true);
if(count(array($data)) > 0)
{
$id_received = mysqli_real_escape_string($connect, $data->send_id);
$name_received = mysqli_real_escape_string($connect, $data->send_name);
$phone_received = mysqli_real_escape_string($connect, $data->send_phone);
$status_received = mysqli_real_escape_string($connect, $data->send_status);
$btnname_received = mysqli_real_escape_string($connect, $data->send_btnName);
if($btnname_received == 'ADD'){
$query = "INSERT INTO society_tour(id,name, phone, status) VALUES ('$id_received','$name_received', '$phone_received','$status_received')";
if(mysqli_query($connect, $query))
{
echo "Data Inserted...";
}
else
{
echo 'Error';
}
}
?>
Not entirely sure about the PHP part, but as you have json_decode in PHP, its safe to assume that PHP expects a JSON content-type
If so, here is how to post data to a url
var postUrl = 'insert.php'; // please check whether the url is correct
var dto = {
'send_id': $scope.id,
'send_name': $scope.name,
'send_phone': $scope.phone,
'send_status': $scope.status
};
$http({
url: postUrl,
method: 'POST',
data: dto,
headers: {
"Content-Type": "application/json"
}
})
//...
I get a value of "True" in my response. How come my debugger and alert and AccessGranted() in the .then of my $http is not being invoked. Below is my Script:
app.controller("LoginController", function($scope, $http) {
$scope.btnText = "Enter";
$scope.message = "";
$scope.login = function() {
$scope.btnText = "Please wait...";
$scope.message = "We're logging you in.";
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
}).then(function (response) {
debugger;
alert(response.data);
if (response.data == "True") {
AccessGranted();
} else {
$scope.message = response.data;
$scope.btnText = "Enter";
}
},
function (error) {
$scope.message = 'Sending error: ' + error;
});
}
$scope.AccessGranted = function() {
window.location.pathname("/Home/HomeIndex");
}
});
This is in my HomeController
public ActionResult HomeIndex()
{
var am = new AuditManager();
var auditModel = new AuditModel()
{
AccountId = 0,
ActionDateTime = DateTime.Now,
ActionName = "Home",
ActionResult = "Redirected to Home"
};
am.InsertAudit(auditModel);
return View("Index");
}
Please see image for the response I get.
seems like your approach is wrong
$http({
method: 'GET',
url: '/someUrl'
}).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.
});
Try this,
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
})
.then(function (response) {
console.log(response);
},
function (error) {
console.log(error);
});
And check your browser console for logs or any errors
Make sure the response is application/json content type, and content is json.
You can also write own httpProvider for check result from server
module.config(['$httpProvider', function ($httpProvider) {
...
I would suggest you to code like this instead of then so whenever there is success, The success part will be invoked.
$http.get('/path/').success(function (data) {
$scope.yourdata = data.data;
//console.log($scope.yourdata);
}).error(function (error){
//error part
});
Am trying to hit web service with a directive controller, I hit the post method and got the response, but values I expected are become empty because all compiled before the success response.
This is my controller within the directive
controller: ['$scope', '$http', 'popupService','SessionUtils', function($scope, $http, popupService,SessionUtils) {
$scope.responseValue = "";
$scope.sendCSVFile = function(link, fileData) {
$scope.seriveResponse = $http({
method: "POST",
url: link,
data: fileData,
headers: {
'Content-Type': undefined
}
}).success(function(response) {
if(response.status == "FAILURE"){
popupService.showErrMsg(response.message);
return false;
}
else {
$scope.responseValue = response;
//SessionUtils.updateResponse(response);
var success = "File Uploaded Successfully";
popupService.showSuccessMsg(success);
return response;
}
return $scope.responseValue = response;
});
});
and I called the controller from the directive link function like
var res = scope.sendCSVFile(attrs.getUrlModel, formData);
scope.gridUpdate(res);
the value res returning undefined, but I get the response after I binded the res. How to I get the promising response and execute the function after.!
You can get promise, not standard data, ajax is asynchronous call, so change code to:
$scope.sendCSVFile = function(link, fileData) {
return $http({ //return promise object
method: "POST",
url: link,
data: fileData,
headers: {
'Content-Type': undefined
}
}).success(function(response) {
if(response.status == "FAILURE"){
popupService.showErrMsg(response.message);
return false;
}
else {
$scope.responseValue = response;
//SessionUtils.updateResponse(response);
var success = "File Uploaded Successfully";
popupService.showSuccessMsg(success);
return response;
}
return $scope.responseValue = response;
});
});
usage:
$scope.sendCSVFile(attrs.getUrlModel, formData).then(function(response){
//here ajax is completed and in response variable You have raturn from success callback
if (response)
scope.gridUpdate(response);
});
This code fetches categories and give them to controller.
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function() {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
if ( SuperCategories.length == 0 ) {
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
});
}else {
return $q.when(SuperCategories);
}
}
return SCService;
});
I think code is perfect until there is no error in http request.
My query is how to do error handling (try catch or something like that), in case if server have some issue or may be cgi-script have some issue and not able to server the request.
Angular promises use a method catch for that.
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
});
You should use also finally :
return $http(req).then(function (response) {
SuperCategories = response.data;
return SuperCategories;
}).catch(function(error) {
// Do what you want here
}).finally(function() {
// Always executed. Clean up variables, call a callback, etc...
});
Write like
return $http(req).then(function (response) {
//success callback
},
function(){
//Failure callback
});
Use callback methods from controller Like
Controller.js
service.GetSuperCategories(function (data) {console.log('success'},function (error){console.log('error'});
service.js
sampleApp.factory('SCService', function($http, $q) {
var SuperCategories = [];
var SCService = {};
SCService.GetSuperCategories = function(successMethod,errorMethod) {
var req = {
method: 'POST',
url: SuperCategoryURL,
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: "action=GET"
};
return $http(req).then(successMethod(data),
errorMethod(error));
}
return SCService;
});
You can use the .success and .error methods of $http service, as below
$http(req).success(function(data, status, headers){
// success callback: Enters if status = 200
}).error(function(status, headers){
// error callback: enters otherwise
});