Below I've got a function that should make a post to the server.
var updateApplicationMetadata = function(appId, editorVersion, previewPubFile){
var deferred = $q.defer();
var result = $http({
method: 'post',
url: '../resource/applications/'+appId,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: {
editorVersion: editorVersion,
previewPubFile: previewPubFile
}
});
result.then(function(data){
deferred.result(data);
console.log('from services: ');
console.log(data);
});
return deferred.promise;
};
I call this function like:
$scope.update = function(){
MessageBus.emitMsg('notification','Application updates successful.');
console.log('from update: ');
console.log($scope.application.appId);
console.log($scope.application.editorVersion);
console.log($scope.application.previewPubFile);
DataContext.updateApplicationMetaData($scope.application.appId,$scope.application.editorVersion ,$scope.application.previewPubFile);
};
All of the values sent to the updateApplicationMetaData are valid. I can use the rest client POST man and I can make the post work. When I do it in angular, however, I get a bad request. The URL and header content type are right, but I'm not sure about the data object. It must be malformed. What am I missing here?
You've got an error in your code. You have:
deferred.result(data);
and it should be:
deferred.resolve(data);
for it to work. Also, you need to pass 'application/json' as your accepts type for your data to work.
Assuming you are using the $q service from https://docs.angularjs.org/api/ng/service/$q I don't see a result method. Perhaps change:
deferred.result(data);
To
deferred.resolve(data);
consider using ngResource for rest style json requests
Angular resource docs
Related
I want to call a php method using angular service. I do this :
save:function(){
var req = {
method: "GET",
url: "/api/save/",
data: {
nom:"nom"
}
}
var deferred = $q.defer();
$http(req).
success(function(result) {
console.log(req);
deferred.resolve(result);
})
and in my php controller :
public function savePersonnelAction(Request $httpRequest){
$content= $httpRequest->query->get('data');
return $this->render('clientBundle:Default:index.html.twig',array('content'=>$content));
}
But I have an empty object as a result.
Can someone help me to resolve this problem please
Do you only want to send some data in a query string?
For a GET request, you should use params, not data attribute.
data is used for a POST request content.
Try like this:
$content= $httpRequest->query->get('nom');
Cheers
Hello guys I really need help and advice on this factory and controller issue I am having.
I have a factory that gets data from the server
sp.factory('homeFeed',['$window','$http','auth',function($window,$http,auth){
var url = auth.url;
var version = auth.version;
var HomeFeed = {};
HomeFeed.getFeeds = function(user){
//setting variable for get request on home feed
var req = {
method: 'GET',
url: url + version + '/Feed',
headers: {
'Content-Type': 'application/json; charset=utf-8',
'Authorization': 'Bearer ' + token
},
}
return $http(req).success(function(res){
return res;
});
};
return HomeFeed;
}]);
controller--
sp.controller('HomeCtrl',['$scope','homeFeed','$window',function($scope,homeFeed,$window){
//getting all the home feed data
$scope.feeds = homeFeed.getFeeds(JSON.parse($window.localStorage['SP-User']))
}]);
however, after the respond from the server, my view is not updated and the $scope.feeds is not updated as well. Greatly appreciate your help
As you are doing async $http call then that data would not be available at that instance of time. It would be available when ajax call succeeded. You need to use .then function which will create a promise chain and will execute a function when .success function returns a data.
Controller
sp.controller('HomeCtrl',['$scope','homeFeed','$window',
function($scope,homeFeed,$window){
//getting all the home feed data
homeFeed.getFeeds(JSON.parse($window.localStorage['SP-User']))
.then(function(data){
$scope.feeds = data
});
}
]);
I am stuck on some problems , actually I was in problem solved , the problem was header which is not enableing to get response (like CORS issue) ,overcome by using header and transformRequest as shown in below code. After that I got webservice data but in one controller used $rootscope which render some of id of data of second method (API) to use in another controller to put on third one api to get data and I am getting this for only a minute then it will throw error : Cannot read property 'companies data' of null which is field in third api. when I used $rootScope.Test.companies[0].companyname which is store data, and unique for all api like primary key.
var request = $http({
method: "post",
url: "http://app.xyz/xyzapp/public/user/login",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
str.push(encodeURIComponent('email_id') + "=" + encodeURIComponent('demo#xyz.com'));
str.push(encodeURIComponent('password') + "=" + encodeURIComponent('demo#xyz'));
return str.join("&");
},
});
request.success(function( response ) {
console.log("Hiiiii::::"+JSON.stringify(response,status));
if (response.status=="success"){
$rootScope.Test1=response.user_id;
var request1 = $http({
method: "post",
url: "http://app.xyz/xyzapp/public/company/getUserCompanyList",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
str.push(encodeURIComponent('user_id') + "=" + encodeURIComponent(response.user_id ));
// str.push(encodeURIComponent('password') + "=" + encodeURIComponent('demo#123'));
return str.join("&");
}
});
// getCompany
request1.success(function( response ) {
console.log("Hiiiii::::"+JSON.stringify(response,status)+" "+response.companies.length+":Length");
if (response.status=="success"){
// alert(1);
$state.go('tabdash');
$rootScope.Test = response;
}
});
So please tell me how to use one controller data to another where I am using another api which will get $rootscope date of parent.
Please let me know if anybody know about that or anything
Thanks
Yes you can use variables of one controller inside another controller using two methods
Create Service to communicate between them.
Use $rootScope.$broadcast
sample code
angular.module('myservice', []).service('msgBus', function() {
this.serviceValue= {};
}]);
});
and use it in controller like this:
controller 1
angular.module('myservice', []).controller('ctrl1',function($scope, msgBus) {
$scope.sendmsg = function() {
msgBus.serviceValue='Hello';
}
});
controller 2
angular.module('myservice', []).controller('ctrl2',function($scope, msgBus) {
$scope.checkValue(){
alert( msgBus.serviceValue);
}
});
I want to create an autocomplete with Angular and since this is my first contact with angular, I`m pretty stucked.
Here is my code:
MenuService.getAutocompleteData(term).then(function (response) {
$scope.menuData = response.data;
});
This is how I call a service that is making the following http call:
return $http({
url : autocompletePath,
method : "POST",
data : {
term: term
}
}).success(function (response) {
return response;
});
The problem is that it seems that is syncronously and my browser freezes when I type fast letters. I saw that it is about that ".then" promise, but I`m not sure how to fix it. Any help would be appreciated.
You do a HTTP-request, which is correct, but you try to return the result on success. Instead you should try to do what needs to be done in your success-handler.
So in your service you would do something like this:
return $http({
url : autocompletePath,
method : "POST",
data : {
term: term
}
}); //note that there is no success handler in your service, because what's supposed to happen when the request completes, is the controller's business, not the service's. The service should only know where to get the data
And you would change your controller to this:
MenuService.getAutocompleteData(term).success(function (response) {
$scope.menuData = response.data;
}); //note the success-handler
Why dont you give this a try?
https://angular-ui.github.io/bootstrap/#/typeahead
I'm trying to send JSON data to my web server via jQuery and I'm running into an error.
Uncaught TypeError: Cannot use 'in' operator to search for 'context' in {"id":45,"isRead":true}
code I am testing:
var obj = {};
obj.id = 45;
obj.isRead = true;
var data = JSON.stringify(obj);
var url = "/notification/read"
$.ajax(url, data, 'application/json', function() {
// code remove notification from the DOM
});
});
Is there a better or more correct way to do this? Not sure if I'm getting the params right on the $.ajax call either.
UPDATE
code I got to work
var obj = {
id: 45,
isRead: true
};
var json = JSON.stringify(obj);
var url = "/notification/read"
$.ajax({ url: url,
type:'POST',
contentType: 'application/json',
data: json,
success: function(data, textStatus) {
// do stuff
}
});
My server was expecting JSON data POSTed as application/json. So was I wrong in thinking I needed all these variables? without these it was sent as a GET and was application/x-www-form-urlencoded. Without the stringify it also didn't work.
You are passing too many arguments to the ajax function: http://api.jquery.com/jQuery.ajax/
Also, the JSON.stringify call is not necessary, jQuery will take care of that for you.
var obj = {
'id':45,
'isRead':true
};
$.ajax({
url: "/notification/read",
data: obj,
success: function(data, textStatus){
/* code here */
}
});
$.ajax(url, obj);
You need to send an object as second param
{success: success, data: data}
Documentation is here:
http://api.jquery.com/jQuery.ajax/
You have to pass parameters as one object, not multiple ones