Angular $http(...).success is not a function help rewriting the function - javascript

I'm trying to fix a website for a group I volunteer for.
I'm trying to update it from Angular 1.3.16 to Angular 1.6.4, but I'm getting an error message that says:
TypeError: $http(...).success is not a function
at b.$scope.init (angular-custom.js:107)
The code that seems to be causing it from what I can tell by debugging it is the angular-custom.js file with the .success and .error functions:
$scope.init = function(){
$http({
method: 'post',
url: url,
data: $.param({ 'type' : 'getUsers' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
success(function(data, status, headers, config) {
if(data.success && !angular.isUndefined(data.data) ){
$scope.post.users = data.data;
}else{
$scope.messageFailure(data.message);
}
}).
error(function(data, status, headers, config) {
//$scope.messageFailure(data.message);
});
};
I have also put the files up at plunker The 1.3.16 files at Plunker
I understand that it might be the .success and .error results, but I don't know Angular that much in how to fix it.
I'm a bit of a self-taught coder so any help would be great so I can this group up and running.
Thanks in advance for any advice.
Rod

I recommend you to read this article
Don't use $http's .success()
And
$http({
method: 'post',
url: url,
data: $.param({'user' : $scope.tempUser, 'type' : 'save_user' }),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).
then(function(response) {
your code
excuted when post request is success
},function(response) {
your code
excuted when post request is failed
});
response is returned from server, you can debug to explore more deeply.

For angular 1.6.4 use .then and .catch to deal with the response and the error respectfully:
(note you can save some lines of code by using $http.post)
$scope.init = function(){
$http.post('yourURL', $scope.yourData).
then(function(results) {
if(results.data.success ){
$scope.post.users = results.data;
}else{
$scope.messageFailure(results.data.message);
}
}).
catch(function(results) {
//$scope.messageFailure(results.data.message);
});
};

Thanks everyone for your help, it seems that I really need to take some time out and learn Angular as I really don't understand how it works.
I found that the person before me got the code from AngularJS Insert Update Delete in PHP and MySQL
But it seems that it pops up in a few places on the net as others claiming the code as theirs. Pity about that.
Again thanks for the input but I think I can get it working on ver 1.5.11 and I'll just have to work it out at a later date.
Rod

Related

Cannot get the cookie in angular even using $cookies

I have seen all the questions regarding this topic in SO.However I cannot seem to get the cookie value even after implementing.I am a newbie at this.So please forgive me for the lack of understanding.
I am sending correct login credentials via angular ajax to server which is returning a Set-Cookie property having a value.I cannot get this cookie value even after using $cookies and implementing it within $timeout.
Below is my service code:
userOperation.loginService = function(username,password){
return $http({
method: 'POST',
withCredentials: true,
url: urlService.baseUrl+'login',
headers: {'Content-Type': 'application/x-www-form-urlencoded','Accept':'application/x-www-form-urlencoded'},
data:"username="+username+"&password="+password+"&AUTH_TYPE=RESTAUTH",
}).then(function successCallback(response){
console.log(response);
return response;
},function errorCallback(response){
console.log(response);
return response;
});
}
And the controller implementing it
app.controller('logInCtrl',function($scope,$http,$browser,$cookies,userOperation,pnotifyService,$rootScope,$timeout){
$scope.login = function(){
userOperation.loginService($scope.username,$scope.password).then(function(response){
console.log(response);
$timeout(function(){
console.log($cookies.get('JSESSIONID'));
console.log($cookies);
},4000);
});
}
});
The response is null object;
But using advanced rest client i am getting the cookie value.Below is the screenshot.
Thanks for your time.
Note:All angular cdns are of version 1.5.8.

How to use Jquery $.Ajax in angularjs

I am trying to use normal jQuery Ajax in anuglarjs .
$.ajax({
type: "POST",
url: window.apirooturl + "/logger",
contentType: "application/json",
data: angular.toJson({
url: $window.location.href,
message: errorMessage,
type: "exception",
stackTrace: stackTrace,
cause: ( cause || "")
})
});
But i am getting an error
Below two messages appears in the firbug
$ is not defined
Error: [$rootScope:inprog] $digest already in progress
Do we need to configure something to use normal jquery function in anagularjs?
I tried to look on Google but could not get a answer
More information :
I am trying to send client side error to the server side and trying to implement a global exception handler as suggested in this post .
http://www.bennadel.com/blog/2542-logging-client-side-errors-with-angularjs-and-stacktrace-js.htm
You are not supposed to use $.ajax in angular you need to use $http request
for example, this is ho you should use post:
$http({
url: "http://example.com",
method: "POST",
data: {"a":"b"}
}).success(function(data, status, headers, config) {
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
please see more at : https://docs.angularjs.org/api/ng/service/$http
1) If you reference full jQuery library, Angular should use it instead of it's own. Do you reference it before angular.js file?
2) Wrap your code with $timeout to prevent error '$digest already in progress'

$http angularjs shows error on callback

I tested my php alone and it gave me this result
{"tabId":1,"tabName":"Main","uId":"1"}{"tabId":2,"tabName":"Photography","uId":"1"}
but my angularjs can't receive the callback, it return an error somewhere in angularjs
userId = '1';
$http({
url: "php/loadTab.php",
method: "GET",
params: {'userId':userId}
}).success(function(data, status, headers, config) {
console.log(data);
}).error(function(data, status, headers, config) {
});
the wierd thing I reuse the exact ajax code and it worked previously. Any thought on this?
the error : SyntaxError: Unexpected token {
at Object.parse (native)
the more strange thing : I purposely add another echo on my php and it able to console the value. what?!
The data from the server isn't valid JSON.
$httpProvider.defaults.transformResponse will try to parse the JSON if the data looks like JSON.
https://docs.angularjs.org/api/ng/service/$http
To fix this you could make the parent an array of objects like this
[{"tabId":1,"tabName":"Main","uId":"1"},{"tabId":2,"tabName":"Photography","uId":"1"}]

Angular $http call not binding on success to $scope.data?

Im having an issue with the $scope.items=data when calling success. I am using this jsfiddle : http://jsfiddle.net/SAWsA/11/ However instead of hardcoded items I did this:
$scope.items=$http({method: 'GET', url: '/test/database/two'}).
success(function(data, status, headers, config) {
return data;
}).
error(function(data, status, headers, config) {
$scope.status=status;
});
and tried this:
$http({method: 'GET', url: '/test/database/two'}).
success(function(data, status, headers, config) {
$scope.items=data;
}).
error(function(data, status, headers, config) {
$scope.status=status;
});
When I put an alert within the success function I see the lenght being 25, so I know i am getting the data. However when I check the $scope.items after this $http run, I get a lengh of undefined after I leave the success function. Like it sets itself and loses it set outside of scope? Any help much appreciated.
When $http runs it will immediately return either [] or {} depending on whether isArray is set or not. The functions you pass to success or error are executed at a later time, when the data is received. When this data is received the [] or {} you had earlier will be populated with the data.
It sounds like you are running $http and testing for the data before it has had chance to be retrieved from the server. If you want to use the data then your relevant code should probably be inside the success function to defer the work until you have the data you want to work with..

Trouble changing Content-Type for POST requests with ngResource (1.0.6 and 1.1.4)

First, I know this question has been asked several times. I have tried many posted solutions and nothing is working for me..
Here are a few other places this was asked:
How to specify headers parameter for custom Angular $resource action
How can I post data as form data instead of a request payload?
Setting application wide HTTP headers in AngularJS
https://groups.google.com/forum/#!msg/angular/Mtsf-YdwwWo/P_Ui4t_DiXkJ
The attempts:
var app = angular.module('theApp', ['app.services']);
app
.config(['$httpProvider', function ($httpProvider) {
// Try (1): This doesn't work
$httpProvider.defaults.headers.common['Content-Type'] = 'application/json;charset=utf-8';
// Try (2): This doesn't work either
$httpProvider.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
}])
angular.module('app.services', ['ngResource'])
// Resource for Drupal system/connect.post API (via services.module)
.factory('SystemConnect', function($resource, $http) {
// Try (3): There's no way this should work. But what the hell let's try!
$http.defaults.headers.common['Content-Type'] = 'application/json;charset=utf-8';
$http.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';
return $resource('api/system/connect.json', {}, {
post: {
method: 'POST',
params: { },
isArray: true,
// Try (4): This doesn't work either
headers: { 'Content-Type': 'application/json;charset=utf-8' }
}
});
});
function SomeCtrl($scope, SystemConnect) {
// FAIL, this results in "406 Not Acceptable: Unsupported content type application/xml"
$scope.user = SystemConnect.post();
}
app.controller('SomeCtrl', SomeCtrl);
It sounds like many people have solved this before. Could someone kindly let me know the right way to do this?
PS: Weirdly, when running this code in Firefox, Angular uses 'Content-Type: text/plain' for the POST!?
I remember reading you have to include content in a post for it to accept your header changes.
$scope.user = SystemConnect.post({});

Categories

Resources