Success Callback not called when $http post is in method scope - javascript

I am trying to achieve a login functionality using Angular JS on front-end and PHP + Zend on the back-end. Below is the code snippet of the angular js controller. This doesn't redirect the user to the appropriate page and while debugging, the control doesn't enter the success part but enters the error part with data being NULL. However if I put the $http part outside the function, atleast the control enters the success part with data being that of the next page to be redirected.
What could i be missing and what is the correct way to achieve the redirection?
In the below code the control doesn't enter the success section.
var myApp = angular.module('myApp',[]);
myApp.controller('loginCtrl', function ($scope, $http) {
$scope.authenticatelogin = function () {
$http({
url: "/admin/auth/authenticatelogin",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({login: $scope.login, password: $scope.password, rememberMe: $scope.remember})
}).success(function(data, status, headers, config) {
$window.location.href= "index/index";
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
};
});
In the below code the control enters the success section.
var myApp = angular.module('myApp',[]);
myApp.controller('loginCtrl', function ($scope, $http) {
$http({
url: "/admin/auth/authenticatelogin",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({login: 'abc#abc.com', password: 'xyzxyz', rememberMe: ''})
}).success(function(data, status, headers, config) {
$window.location.href= "index/index";
$scope.data = data;
}).error(function(data, status, headers, config) {
$scope.status = status;
});
});

I would rather go for success/error callbacks to be part of the then method.
From angular documentation for version 1.4.5:
The $http legacy promise methods success and error have been
deprecated. Use the standard then method instead. If
$httpProvider.useLegacyPromiseExtensions is set to false then these
methods will throw $http/legacy error.
Try this one, although if you say that your code works outside the closure, it might not be the solution you are looking for:
$http({
url: "/admin/auth/authenticatelogin",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({login: $scope.login, password: $scope.password, rememberMe: $scope.remember})
}).then(function(data, status, headers, config) {
$window.location.href= "index/index";
$scope.data = data;
}, function(data, status, headers, config) {
$scope.status = status;
});

Related

Adding $http request bricks Ionic app

I'm trying to add a post request to a button in my ionic app but I've found that adding the code makes the app useless. Not a single thing responds to any of my taps. Removing the code makes things normal again. This is all I have added:
$scope.powerPrompt = function() {
var pwr = alert("Power On");
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$http({
method: 'POST',
url: 'url',
data: "string"
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
// handle success things
})
.error(function(data, status, headers, config) {
// handle error things
})
};
If I delete everything inside the powerPrompt function except the var pwr line, the rest of my app works. What's causing this? Do I have a syntax issue?
You are missing a , after the data property
$scope.powerPrompt = function() {
var pwr = alert("Power On");
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$http({
method: 'POST',
url: 'url',
data: "string",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(response) {
// handle success things
})
.error(function(data, status, headers, config) {
// handle error things
})
};

How to replace ajax call with $http, AngularJs

I am trying to implement angular.js in my php file, Because it's only one file project, So I am thinking where I use AngularJS. So i decided to replace AJAX call with $http.
For this i imported google angular js file
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
And replace my this ajax call
$.ajax({
url: url,
type: "GET",
data: data,
async: false,
success: function(res) {
resData = res;
}
});
With
$http({
url: url,
method: "GET",
data: data
}).success(function(data, status, headers, config) {
resData = data;
}).error(function(data, status, headers, config) {
resData = data;
});
beside these nothing changed, but when i am trying to execute my code, I am getting this error
$http is not defined
In order to use $http you first need to inject it into your controller
var module = angular.module('putNameHere', [])
module.controller('myCtrl', ['$http', function($http){ //injection here
$http({
url: url,
method: "GET",
data: data
}).success(function(data, status, headers, config) {
resData = data;
}).error(function(data, status, headers, config) {
resData = data;
});
}])
You are going to have to actually load an angular module and controller, then inject $http into the controller:
<script>
var app = angular.module('app', []);
app.controller('HttpCtrl', function($http) { //this is the $http injection here
//insert your $http code here
})
</script>
Plunker Demo (change google.com to whatever url you need to use)
You will also need to add the ng-app='app' attribute to your <html> tag, and the ng-controller='HttpCtrl' attribute to your <body> tag.
The $http service is a function which takes a single argument — a configuration object — that is used to generate an HTTP request and returns a promise with two $http specific methods: success and error.
$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.
});
source https://docs.angularjs.org/api/ng/service/$http

Angular $http.post not returning XML

I am trying to call a web service with angular, but not having much luck. The service takes a POST request with no POST body, and returns XML. I can confirm that the service works with a raw XMLHttpRequest call:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function(){
if(xhr.readyState == 4)
console.log(xhr.responseText); // Returns data
}
xhr.open("POST", "https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML", true);
xhr.send(null);
And with jQuery:
$.ajax({
url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML',
type: "POST",
success: function(data){
console.log(data); // Returns data
},
error: function (hxr, status, errorThrown){
console.log(status);
}
});
However, I'm not getting anything back when I try it with angular's $http service:
angular.module('TestApp',[])
.controller('TestController', function($scope, $http){
$http({
method: "POST",
url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML'
}).success(function(data, status, headers, config){
console.log("data:");
console.log(data); // Returns null
}).error(function(data, status, headers, config){
console.log("error status:");
console.log(status); // No errors returned
})
})
EDIT: Using the $http.post shortcut method:
angular.module('TestApp',[])
.controller('TestController', function($scope, $http){
$http.post(
'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML'
).success(function(data, status, headers, config){
console.log("data:");
console.log(data);
}).error(function(data, status, headers, config){
console.log("error status:");
console.log(status);
})
})
Note that the $http.post shortcut method has a second data parameter, but I have no data to pass. If I include the parameter as null, Chrome says:
Request header field Content-Type is not allowed by Access-Control-Allow-Headers
Since the $http.post shortcut method does not complain about missing out the data parameter, I have deliberately missed it out.
I need to be able to make the POST call with no data, as is possible with a raw XMLHttpRequest call, or jQuery's ajax method. What might be going wrong? Thanks!
(NB, the API is public, so don't worry about the API key I've posted. It's a valid API key, which I'll keep active only while this question is open)
Angular by default expecting to get JSON from your server you can change that by adding
var app = angular.module('app', []);
app.controller('homeCtrl', function($scope, $http) {
$scope.xml = "";
$http({
method: "POST",
url: 'https://api.bmreports.com/BMRS/MessageListRetrieval/v1/?APIKey=9eu73tsryf1sons&ParticipantId=INNOGY01&PublicationFrom=1970-01-01&PublicationTo=3000-01-01&ServiceType=XML',
headers: {
"Accept": "application/xml"
}
}).success(function(data, status, headers, config) {
console.log("data:");
console.log(data); // Returns null
$scope.xml = data;
}).error(function(data, status, headers, config) {
console.log("error status:");
console.log(status); // No errors returned
})
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<div ng-controller="homeCtrl">
{{xml}}
</div>
</div>
to your request

variable is not shareable in http $scope

$http({
url: "php/InsertTab.php",
method: "POST",
data: {
'userId': userId,
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
myVar = data;
}).error(function(data, status, headers, config) {
});
console.log(myVar);
can variable myVar be share / be access outside the scope of $http? I wrote console.log(myVar) outside it returned blank?
u have to use angular $q service in order to use myVar outside of $http.
try reading in this page : https://docs.angularjs.org/api/ng/service/$q

$http scope issue with variable

$http({
url: "php/myuId.php",
method: "POST",
data: {
'userId': userId,
},
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).success(function(data, status, headers, config) {
$scope.myId= data;
//return last inserted id
}).error(function(data, status, headers, config) {
});
//can't use it outside?
$scope.user.push({
"userId": $scope.myId,
});
strange, $scope.myId isn't change when I used it outside of scope $http, so I can't push my last inserted id to front end.
The problem is that it is asynchronous, so you don't have the data yet until the promise returns. You could either put the $scope.user.push inside the success callback, or use $scope.$watch("myId"... to register when the value is updated.
Try using .apply(); The change in JS won't be seen, or reflected in the UI if you don't.
}).success(function(data, status, headers, config) {
$scope.apply(function(){
$scope.myId = data;
});
})

Categories