Angular $http request in the controller does not work - javascript

I have the following controller. It works all fine (it parses the data and sends them into the view). The only problem I have is that it does not send $http request. Here is the code block of controller (i just send a test $http without any value from the view just to test it works or not, which does not work):
(It's also worth mentioning that I check via browser's console to see if any ajax request is sent or not)
// Controller
LoginApp.controller("RegisterController", function($scope, $http, registerService){
var username = null;
var password = null;
$scope.registerSubmit = function(){
username = $scope.register.username;
password = $scope.register.password;
};
//registerService.CheckUser();
$http.post('server.php', {name : 'something'})
.success(function(data, status, header, config){
return data;
})
.error(function(data, status, header, config){
return data;
}); // end of $http request
});
EDIT: I have edited what #JoshBeam has recommended, passing data to the post(), but it does not change anything.

You need to pass data along with the HTTP request. According to the AngularJS documentation, it is in this format: post(url, data, [config]);
Thus:
$http.post('server.php', /* your data */);

Related

Ionic post data to server

I found this solution here, but it doesn't explain a lot so I can modify it to my needs. He is also mentioning a stack overflow question, but there are so many "different" solutions and I got confused.
The controller:
.controller('AppCtrl', function($scope, $http) {
$scope.data = {};
$scope.submit = function(){
var link = 'http://app.domain.com/api.php';
$http.post(link, {username : $scope.data.username}).then(function (res){
$scope.response = res.data;
});
console($http.post(link, {username : $scope.data.username}));
};
});
I would like modify it and add another field, so it would be username and password. and post the to the server. But the response I need it to be just one field.
Can someone give me an explanation, of the code above so I can modify it?
As NNR said, you can pass some other parameters in your HTTP request and then POST it to the endpoint of your choice (here, the link, generally an API endpoint) by submitting it through an ng-submit. The request contains your parameters and is parsed into json that you can un-parse later in your php file (in order to get params of the request and then use it in your mysql query (generally..). After the request has been sent, it will return you a promise, that will either be a success or an error based on the reply of your server, like this :.then(function success(response) { //do stuff here},
function error(response) {//do stuff here});
You will be able to access that response.data object in your controller by using $scope
I've some hard time being clear but I hope that helps ! I suggest you to have a look at https://docs.angularjs.org/api/ng/service/$http ! :)

angular-seed POST acts differently for each browser

I'm not sure what is going on with my http post method. From what I was reading, there might be something wrong with my security, but I am not really sure that is the case or how to fix it. Any insight in the right direction would be nice.
I am trying to post to an API and retrieve a response back and return the data. When I run the POST in IE, I get the proper response.
However when I try this in Chrome I get weird results. My POST turns into an OPTIONS method. With a Status Code of 200 OK, but my Response is blank. And when I try to go to the url directly without the POST I get this displayed in the browser:
{"result":false,"error":"Authentication failed: Session authentication failed: No Host Name specified Authentication State: Invalid Login"}
Here is the test.js (controller)
var host = '255.255.255.255';
var creds = {'logintype':'1','host':host,'user':'Administrator','password':'1234','controlid':'ABC999'};
//var obj = JSON.stringify(creds);
angular.module('myApp.test', ['ngRoute'])
.config(['$routeProvider', function($routeProvider) {
$routeProvider.when('/test', {
templateUrl: 'test/test.html',
controller: 'TestCtrl',
resolve: {
friends: ['$http', function($http) {
return $http({url: 'http://192.168.2.164/ISAPI/rip.dll/REST/SESSIONS/',method: 'POST', data: creds })
.success(function (data) {
return data;
})
.error(function () {
return 'Error';
});
}]
}
});
}])
.controller('TestCtrl', ['$scope', 'friends',function($scope,response) {
$scope.response = response;
}]);
Thanks to itsananderson, I was able to resolve my issue. I was happening because Chrome does something called a "preflight" for cross-domain requests. I needed to move the API to be on the same server as the site was being run to avoid cross site scripting.

angularJS sending OPTIONS instead of POST

Im stuck at this 2 days I can not find a solution.
When im doing an AngularJS POST it Sends OPTIONS in the header and returns error from the API the code looks like this nothing special.
$http.defaults.headers.post["Content-Type"] = "application/json";
$http.post(URL, JSON.stringify(data)).
success(function(data, status, headers, config) {
alert(data);
error(function(data, status, headers, config) {
console.log("Error");
});
CORS is enabled on the API it has the Headers, when i do POST with fiddler or POSTMan in Chrome it works fine only when i use angularJS post it won't go thru.
why do i get OPTIONS /SubmitTicket HTTP/1.1 instead of POST?
What do i need to do to POST ? I have read about it it says something like CORS is adding OPTIONS header but why?
When you invoke the CORS requests, the browser always sends the OPTIONS request to server to know what methods are actually allowed. So this is the desired behaviour. This is so called: "Preflighted request", see: http://www.nczonline.net/blog/2010/05/25/cross-domain-ajax-with-cross-origin-resource-sharing/ (section: "Preflighted requests")
Therefore in your case, you have to allow the OPTIONS method in 'Access-Control-Allow-Methods' header of your CORS filter.
My understanding is that angular initially sends an OPTIONS request to the server in order to ask the server if the full request is permissable.
The server will then respond with Headers specifying what is and is not allowed.
I guess this might be an issue with the server returning the wrong CORS headers.
You said that the server returns an error please post that error here.
See Preflighted CORS request at: http://www.staticapps.org/articles/cross-domain-requests-with-cors
and
AngularJS performs an OPTIONS HTTP request for a cross-origin resource
// Simple POST request example (passing data) :
$http.post('/someUrl', {msg:'hello word!'}).
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.
});
Should only need to do this code to get it to work:
angular.module('TestApp', [])
.factory('someService', ['$http', someService]);
function someService() {
var service = {
save: save
};
var serviceUrl = '/some/Url';
return service;
function save(data) {
$http.post(serviceUrl, data)
.success(function(data, status, headers, config) {
alert(data);
})
.error(function(data, status, headers, config) {
console.log("Error");
});
}
}
Then pull your someService into your controller and use:
someService.save(data);

Angular $http.get with dynamic route?

I'm fairly new to angular and I'm trying to understand how to query from a REST API using a scope variable to determine the URI that is being pulled in the get request.
Lets say I'm in my app.controller and it has a service that spits out an array of numbers.. and for the sake of making the code minimal, I'll skip to the important part:
$scope.currentCompanyId = '0001';
$http.get('/api/'+ $scope.currentCompanyId +'/c').
success(function(data, status, headers, config) {
$scope.cData = data;
}).
error(function(data, status, headers, config) {
// log error
});
I know this is cheating because the $http.get is in the controller. I know it needs to be a factory of some kind.. but I have no idea how to pass the $scope.currentCompanyID to the get request and have it return the JSON. Furthermore, if $scope.currentCompanyID were to change to another number, say... '0002'.. how would the $scope.cData change to reflect the new query?
I don't think using $http in your controller is cheating - one reason for putting it into a factory/service is make it reusable. If you are only doing it in one place a service doesn't add much.
That being said, your service can return a function that takes a parameter:
app.factory("service", function($http) {
return {
getCompany: function(companyId) { ...make $http call and return data... }
}
});
then in your controller:
service.getCompany($scope.currentComanyId).then(function(resp) {...})
You should consider using Angular $resource because it handles a lot of your abstractions. Either way, if you want to make a new request based on changes in the scope variable, you can $watch it:
$scope.$watch('currentCompanyId', function() {
if(!$scope.currentCompanyId) return;
$http.get().success(); // replace with whatever mechanism you use to request data
});
Your request wont launch if currentCompanyId change... You need to lauch your request manually .
otherwise, it seem to be correct
Did you look at $resource service? http://docs.angularjs.org/api/ngResource/service/$resource - it is rather convenient way to REST requests, and docs have quite a few examples that should suit you well
About changing $scope.currentCompanyID - it seems that you need to create watch for this case:
scope.$watch('currentCompanyID', function(newValue, oldValue) {
// do your update here, assigning $scope.cData with the value returned
// using your code:
$http.get('/api/'+ $scope.currentCompanyId +'/c').
success(function(data, status, headers, config) {
$scope.cData = data;
}).
error(function(data, status, headers, config) {
// log error
});
});
You simply need to pass the data in when calling your service. In your controller, you would need to include your service as a DI module and address it as so:
window.angular.module('myControllerModule', [])
.controller('myController', ['$scope', 'myHTTPService',
function($scope, myHTTPService){
$scope.currentCompanyId = 1;
$scope.lookupPromise = myHTTPService.get($scope.currentCompanyId);
$scope.lookupPromise.then(function(data){
//things to do when the call is successful
},function(data){
//things to do when the call fails
});
}]);
In your service, you deal with that value like this:
window.angualr.module('myHTTPServiceModule', [])
.factory('myHTTPService', '$http',
function($http){
function callHTTP(url){
return $http.get('/api/' + url + '/c');
}
return {
get: callHTTP
};
});

Handle an express redirect from Angular POST

I'm using Expressjs as an API and I'm using angular to hit that POST. I would like to respond to the redirect that express is sending. Success from my Angular POST returns a HTML of the page I intend to redirect to but nothing happens on my DOM. I can see that my redirect is working in my network traffic, and that console.log data, below contains the DOM of the redirected page.
How can I refresh the DOM, to reflect this successful POST, or handle the "redirect"?
ANGULAR CODE:
$http({method: 'POST', url: '/login', data:FormData}).
success(function(data, status, headers, config) {
console.log(data)
}).
error(function(data, status, headers, config) {
});
$scope.userName = '';
Expressjs API:
app.post('/login', function(req, res){
var name = req.param('name', null); // second parameter is default
var password = req.param('password', "changeme")
// Lots Authenticationcode
// returns succesfful login
res.redirect('http://localhost:3000/');
}); // end app.post
console.log(data) (from Angular POST success)
returns the HTML of the page I intended to redirect to
AngularJS is meant to work as a client-side framework coupled with (mostly) RESTfull APIs. Your login API isn't supposed to return a HTML, it is supposed to return the instruction to redirect. So in your case you should simply call $location.url('/') in your $http success callback, which would use the Angular router to "redirect" to '/' (the root URL).

Categories

Resources