Angular doesn't update my object after http request - javascript

this is my angular code:
samirsoftApp.controller("OrderCtrl",function($scope,$http){
$scope.currentStep=1;
$scope.defaultQuantity=1;
$scope.item={};
$scope.getItem = function(){
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$scope.$apply(function(){
$scope.item = data;
});
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
});
when it request and get answer, it does not update my item object, so I used $apply and it did not work and throw an error:
Error: [$rootScope:inprog] http://errors.angularjs.org/1.3.13/$rootScope/inprog?p0=%24digest
S/<#https://ajax.googleapis.com/ajax/libs/angularjs/1.3.13/angular.min.js:6:417
.....
I also tried
$timeout(function() {
$scope.item = data;
}, 0);
instead of $apply` but it prints a null object in consol
it's like this:
samirsoftApp.controller("OrderCtrl",function($scope,$http,$timeout){
$scope.currentStep=1;
$scope.defaultQuantity=1;
$scope.item={};
$scope.getItem = function(){
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$timeout(function() {
$scope.item = data;
}, 0);
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data)
});
};
});
What should I do for my object to be updated after a http request.
thanks

You can assign the data returned by $http.get() request like this
$http.get('/test/getItemDetails/')
.success(function(data, status, headers, config) {
$scope.item = data;
console.log($scope.item);
})
.error(function(data, status, headers, config) {
console.log(data);
});
};
No need for $apply as angular automatically updates $scope
I suspect the problem is elsewhere with your code
Possibly:
You defined function#getItem which contained the $http request but where did you call it?
Make sure the call to URL /test/getItemDetails/ is
returning data by manually browsing or by using a utility like POSTMAN.
being called with the proper URL - try checking in developer tools > network for 404 Errors
I have updated your code - demo here - http://jsbin.com/notudebiso/1/edit?html,js,output
(using a $http call to github api)

Related

Defer execution of page controller until init data is gathered

I have an SPA. I have some basic init data that I'm fetching from the server that I'm certain that I want to defer every page load until that data is loaded. (this data contains whether the user is logged in, permissions, and other vital stuff). So if I have a service for fetching and accessing that data, a page controller might start execution before I have the data, which is bad.
I can't use a promise either, partly because it doesn't solve my problem that I don't want the page to begin loading, and partly because it can't be updated easily and I don't want to always use a promise to fetch this basic data
this is what i've tried so far:
my service
app.factory('AppData', function($q, $http){
var appData = {};
$http
.post( "/api/GeneralActions/getInitData", {
}).success(function (data, status, headers, config) {
appData = data;
}).error(function (data, status, headers, config) {
});
return {
getAppData: function () {
return appData;
}
};
});
my page controller:
app.controller('MainPreferences', function($scope, AppData){
// when this gets executed, appData is null
$scope.appData = AppData.getAppData();
});
Try following snippet
app.factory('AppData', function($q, $http){
var appData = {};
$http
.post( "/api/GeneralActions/getInitData", {
}).success(function (data, status, headers, config) {
//appData = data;
angular.extend(appData, data);
}).error(function (data, status, headers, config) {
});
return {
getAppData: function () {
return appData;
}
};
});
Instead creating appData object again, just extend it with data . By this way your appData object pointer will not change and controllers will also get updated.
Are you using ngRoute? If so, it sounds like what you want is to have a resolve property on your routes to require them to load something before changing the path to the new route.
See the ngRoute docs and search for resolve.
If you are using the stock Angular ngRoute routing system, you can use the resolve property on the route to specify a map of promise-returning functions. The route controller will not be initialized before these promises are all resolved, and as a bonus, the promises' results are injected into the route controller.
For example:
$routeProvider.when('/foo', {
controller: 'fooCtrl',
resolve: {
bar: function($http) { return $http.get('/load/the/bar'); }
}
});
// bar is injected from the route resolve
myApp.controller('fooCtrl', function($scope, bar) {
$scope.bar = bar;
});
I think it should be:
app.factory('AppData', function($q, $http){
var appData = {};
return {
getAppData: function () {
$http.post( "/api/GeneralActions/getInitData", {}).success(function (data, status, headers, config) {
return data;
}).error(function (data, status, headers, config) {
});
}
};
});

CORS error when POST data in AngularJS & CodeIgniter3

I'm use AngularJS 1.3 and CodeIgniter 3.0.
I success to GET data from php in localhost.
However I have error "Cross-origin-request blocked".
I do not know it but was a search, plese help me.
Javascript
var module = angular.module('app', ['onsen']);
module.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
});
module.controller('MasterController', function($scope, $http) {
$scope.doLogin = function() {
var postData = {"email": "aaa#bbb.ccc", "password": "pass"};
var url = 'http://example/test?callback=JSON_CALLBACK';
//This section is Error
$http.post(url, postData, {withCredentials: true})
.success(function(data, status, headers, config) {
//
}).error(function(data, status, headers, config) {
//
});
//This section is Success
$http.get(url).success(function(data, status, headers, config) {
//
}).error(function(data, status, headers, config) {
//
});
};
});
I tried "$http({url ~})", but It was the same result.
PHP
public function index() {
$input_data = json_decode(trim(file_get_contents('php://input')), true);
$this->output
->set_header("Access-Control-Allow-Origin: *")
->set_header("Access-Control-Expose-Headers: Access-Control-Allow-Origin")
->set_content_type('application/json')
->set_output(json_encode($input_data));
}
Try Using .htaccess to allow CORS. Put this in your server .htaccess file
Header add Access-Control-Allow-Origin "*"
Header add Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Even accessing different port is perceived by browser as cross-domain action, the best guide so far how to enable CORS can be found here http://enable-cors.org/

How to pass function's parameter to $http post in angular js so that this value can sent through $http

//How to pass function's parameter to $http post in angular js so that this value can sent through $http
$scope.abc=function(i,d)
{
alert(id);//Getting value
$http.post('abc.php?flag=pqr',
{
'q' : i,//value is not posting
's' : d ////value is not posting
//How to send value of i and d to abc.php page
})
.success(function (data, status, headers, config) {
alert(data);
alert("Product has been Submitted Successfully");
})
.error(function(data, status, headers, config){
alert("Something went wrong please try again");
});
}

Angular http json request issue

Hello I have a simple question but I'm running into problems. I edited some code that I found on line. I'm trying to utilize an Angular http service to retrieve JSON data but it doesn't seem to be working
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
sucess(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
My code example is below
http://codepen.io/jimmyt1001/pen/dPVveN
You spelled wrong sucess should be success
CODE
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
.success(function(data, status, headers, config) {
$scope.posts = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
you should use a service for this:
json.service('getJson', ['$http', function ($http) {
var promise = null;
//return service
return function () {
if (promise) {
return promise;
} else {
promise = $http.get('url');
return promise;
}
};
}]);
function MainCtrl($scope, getJson) {
getJson().success(function (data) {
$scope.json = data;
});
};
Remember to inject the service name in your controller.
tl;dr
It should be like this:
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http)
{
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
.success(function(data, status, headers, config)
{
$scope.posts = data;
})
.error(function(data, status, headers, config)
{
// log error
});
});
I.e. you're missing a dot (.) before success and your success is incorrectly typed (you type sucess).
Original
Your code should be structured like this:
// Simple GET request example :
$http.get('/someUrl').
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
As explained in the docs.
Yours is like this:
$http.get('https://www.dropbox.com/s/325d678ksplb7qs/names.json')
sucess(function(data, status, headers, config) {
Wherea you're missing a dot (.) before the success, and your success is spelled wrong (yours is sucess).
It's decent practice to copy existing demos until you're certain on how they're really setup. Also, use your developer tools to catch easy bugs like this.
It's also possible that your dropbox call is simply invalid, but if you fix your code accordingly then the error method should be able to catch it and you should be able to see the error.

Sending JSON using $http cause angular to send text/plain content type

I just want to send the following JSONobjects to my API backend:
{
"username":"alex",
"password":"password"
}
So I wrote the following function, using Angular $http:
$http(
{
method: 'POST',
url: '/api/user/auth/',
data: '{"username":"alex", "password":"alex"}',
})
.success(function(data, status, headers, config) {
// Do Stuff
})
.error(function(data, status, headers, config) {
// Do Stuff
});
I read in documentation for POST method that Content-Type header will be automatically set to "application/json".
But I realized that the content-type I receive on my backend (Django+Tastypie) api is "text/plain".
This cause my API to not respond properly to this request. How should I manage this content-type?
The solution I've moved forward with is to always initialize models on the $scope to an empty block {} on each controller. This guarantees that if no data is bound to that model then you will still have an empty block to pass to your $http.put or $http.post method.
myapp.controller("AccountController", function($scope) {
$scope.user = {}; // Guarantee $scope.user will be defined if nothing is bound to it
$scope.saveAccount = function() {
users.current.put($scope.user, function(response) {
$scope.success.push("Update successful!");
}, function(response) {
$scope.errors.push("An error occurred when saving!");
});
};
}
myapp.factory("users", function($http) {
return {
current: {
put: function(data, success, error) {
return $http.put("/users/current", data).then(function(response) {
success(response);
}, function(response) {
error(response);
});
}
}
};
});
Another alternative is to use the binary || operator on data when calling $http.put or $http.post to make sure a defined argument is supplied:
$http.put("/users/current", data || {}).then(/* ... */);
Try this;
$http.defaults.headers.post["Content-Type"] = "application/json";
$http.post('/api/user/auth/', data).success(function(data, status, headers, config) {
// Do Stuff
})
.error(function(data, status, headers, config) {
// Do Stuff
});

Categories

Resources