I have loaded a page using AngularJS. I have the following code:
var app = angular.module("adhocAnalytical",[]);
app.controller(
"ReportController",
function ($scope,$http) {
$http({
method: 'POST',
url: '/campustoolshighered/k12_reports_adhocreport4_analytical_body.do',
data: 'action=fetchinitdata',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response) {
$scope.questions = response;
});
}
);
angular.element(document).ready(function (){
angular.bootstrap(document,['adhocAnalytical']);
});
When we load a page second time in a current session using AngularJS, it does not load. It give only the expression written on the jsp page such as:
{{question.title}}
{{cell.f}}{{cell.f}}
{{row.h}} {{row.v}} {{row.v}}
Remove }; after the success callback:
app.controller(
"ReportController",
function ($scope,$http) {
$http({
method: 'POST',
url: '/campustoolshighered/k12_reports_adhocreport4_analytical_body.do',
data: 'action=fetchinitdata',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
.success(function(response) {
$scope.questions = response;
});
}
);
Related
I am making a post request to an api with submit() function which is attached to a ng-click directive sending the data in JSON format, it returns this error.
It is running fine on postman so the error is on client side only.
Also the email and selectedIds variables are not empty.
Here is my controller file:
app.controller('categoryController', ['$scope', '$rootScope', '$sce', '$http', '$timeout','$window', function($scope, $rootScope, $sce, $http, $timeout, $window) {
$scope.allCategories = {};
$http({
method: 'GET',
url: 'http://qubuk.com:8081/api/v1/alltag'
})
.then(function (data) {
// console.log("DATA:" + JSON.stringify(data.data.categories[0].displayName));
// console.log("DATA category:" + JSON.stringify(data.data.categories));
$scope.allCategories = data.data.categories;
});
$scope.selectedIds = [];
$scope.change = function(category, active){
if(active){
$scope.selectedIds.push(category.id);
}else{
$scope.selectedIds.splice($scope.selectedIds.indexOf(category.id), 1);
}
// console.log("SELECTED IDS:" + $scope.selectedIds);
};
$scope.email = "faiz.krm#gmail.com"
console.log("email is "+ $scope.email);
$scope.submit = function () {
var tagsData = {"emailId": $scope.email,
"tagsId": $scope.selectedIds};
console.log("tagsData:" + JSON.stringify(tagsData));
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: tagsData
})
.then(function (data) {
console.log("Ids sent successfully!");
alert("successful");
$window.location.href = '/app/#/feed';
})
};
// console.log("amm Categories:" + JSON.stringify($scope.allCategories));
}]);
edit: the response is not a JSON object... it is a string. I do think error is due to this only... how can i resolve it on the front end...
Try to add:
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
to your request:
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: tagsData,
headers : { 'Content-Type': 'application/x-www-form-urlencoded'}
})
Alternately try to pass a stringify data:
$http({
method:'POST',
url: 'http://qubuk.com:8081/api/v1/user/update/tags',
data: JSON.stringify(tagsData),
headers: {'Content-Type': 'application/json'}
})
I want to make an $http request making use of the configuration object instead of the quick method. The request is of 'GET' method and the url targets a local json file.
The code looks more or less like:
$http.get({
method: 'GET',
url: 'data.json'
}).then(function(res) {
$scope.data = res;
}, function(res) {
console.log(res);
})
The error I get is :
Error: [$http:badreq]
Here's a 'working' plunker demonstrating the problem.
The fact is that if I use the quick method $http.get('clients.json') it works.
Any help would be appreciated.
update your app.js file
var app = angular.module('app', []);
app.controller('MainCtrl', function($scope, $http) {
$http({
url: 'data.json',
type: 'GET'
}).then(function(res) {
$scope.data = JSON.stringify(res.data);
}, function(res) {
console.log(res);
})
});
DEMO
try this it works for me : plunker
app.controller('MainCtrl', function($scope, $http) {
$http({method: 'GET',url : './data.json'}).then(function(res) {
$scope.data = res;
}, function(res) {
console.log(res);
})
});
First on your index.html, you had {data}} instead of :
<body ng-controller="MainCtrl">
{{data}}
</body>
On your controller you have to invoke the $http as following (not using $http.getbut just $http) :
$http({
method: 'GET',
url: 'data.json'
}).then(function successCallback(response) {
$scope.data = response.data;
}, function errorCallback(response) {
console.log(response);
});
See working update here https://plnkr.co/edit/OCPkPYsbcHv2snef5Bj3?p=preview
Seems your code is wrong, you already use $http.get, but still add {method: 'GET'}.
I guess you want to use $http request directly.
$http({
method: 'GET',
url: 'data.json'
}).then(function(res) {
$scope.data = res;
}, function(res) {
console.log(res);
})
app.service('customersService', function ($http) {
this.getCustomer = function (id) {
$http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
}).success(function(data) {
console.log(data);
return data;
})
};
});
Cannot get the data in the controller from the service
The problem with this code is when i try to run this
customersService.getCustomer(customerID).then
It generates an error mentioned below:
angular.js:13294 TypeError: Cannot read property 'then' of undefined.
The main thing is the call to the service is generated and if i try to print the results on the console in the service the data is there. However i cannot get the data in my controller.
You get that error becuase you are not returning the promise from $http GET request.
Edit your code like this:
app.service('customersService', function ($http) {
this.getCustomer = function (id) {
return $http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
});
};
});
And then with .then() in your controller, you handle the response data.
app.controller('myController', function($scope, customerService){
customersService.getCustomer(customerID)
.then(function(response){
$scope.data = response;
})
})
You simply forget to return the $http promise that is why undefined is returned. You need to do the following:
...
return $http({ ...
Try given code.
app.service('customersService', function ($http) {
var getCustomer = function (id) {
return $http({
method: 'GET',
url: '/getCustomer',
params: {id: id},
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
})
};
var customersService = {
getCustomer: getCustomer
}
return ProfileService;
});
How to get the response from Service in below case??
Service:
app.factory('ajaxService', function($http) {
updateTodoDetail: function(postDetail){
$http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
})
.success(function(response){
//return response;
});
}
})
Controller:
updated_details = 'xyz';
ajaxService.updateTodoDetail(updated_details);
In th above case, i POST the data through Controller and it was working fine but now i want the response to come in my Controller.
How to achive that??
$http returns a promise:
Return the promise
updateTodoDetail: function(postDetail){
return $http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
});
So you can do
ajaxService.updateTodoDetail(updated_details).success(function(result) {
$scope.result = result //or whatever else.
}
Alternatively you can pass the successfunction into updateTodoDetail:
updateTodoDetail: function(postDetail, callback){
$http({
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
url: post_url,
data: $.param({detail: postDetail})
})
.success(callback);
So your controller has
ajaxService.updateTodoDetail(updated_details, function(result) {
$scope.result = result //or whatever else.
})
I would prefer the first option so I could handle errors etc as well without passing in those functions too.
(NB: I haven't tested the code above so it might require some modification)
what I usually do is like this
app.factory('call', ['$http', function($http) {
//this is the key, as you can see I put the 'callBackFunc' as parameter
function postOrder(dataArray,callBackFunc) {
$http({
method: 'POST',
url: 'example.com',
data: dataArray
}).
success(function(data) {
//this is the key
callBackFunc(data);
}).
error(function(data, response) {
console.log(response + " " + data);
});
}
return {
postOrder:postOrder
}
}]);
then in my controller I just call this
$scope.postOrder = function() {
call.getOrder($scope.data, function(data) {
console.log(data);
}
}
do not forget to insert the dependency injection of 'call' services into your controller
i want to change post['Content-Type'] in angularjs so i use
app.config(function($locationProvider,$httpProvider) {
$locationProvider.html5Mode(false);
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
});
and the event is
$http.post("http://172.22.71.107:8888/ajax/login",{admin_name:user.u_name,admin_password:user.cert})
.success(function(arg_result){
console.log(arg_result);
});
};
however the rusult is
Parametersapplication/x-www-form-urlencoded
{"admin_name":"dd"}
what i want is
Parametersapplication/x-www-form-urlencoded
admin_name dd
so what i should do?
Try like:
var serializedData = $.param({admin_name:user.u_name,admin_password:user.cert});
$http({
method: 'POST',
url: 'http://172.22.71.107:8888/ajax/login',
data: serializedData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}}).then(function(result) {
console.log(result);
}, function(error) {
console.log(error);
});
angular.module('myApp', [])
.config(function ($httpProvider) {
$httpProvider.defaults.headers.put['Content-Type'] = 'application/x-www-form-urlencoded';
$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
})
OP is using Content-Type : application/x-www-form-urlencoded so you need to use $httpParamSerializerJQLike to change post data from JSON to string
note: there is no data property but is params property
$http({
method: 'POST',
url: 'whatever URL',
params: credentials,
paramSerializer: '$httpParamSerializerJQLike',
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
Additionally, you can inject the serializer and use it explicitly with data property
.controller(function($http, $httpParamSerializerJQLike) {
....
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
Have a look at this:
How can I post data as form data instead of a request payload?
Alternatively, you could do the following:
$http.post('file.php',{
'val': val
}).success(function(data){
console.log(data);
});
PHP
$post = json_decode(file_get_contents('php://input'));
$val = print_r($post->val,true);