Ionic post data to server - javascript

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 ! :)

Related

<a href> Post request always returns to wrong URL Angular

Im trying to execute a like POST request with a in angular. The url gets filled in correctly as you can see
In the code it looks like this
But everytime it gives a 405 method not allowed (http://dressfriends.app) and returns to http://dressfriends.app
I do the exact samething with PHP without angular and this works
Anyone an idea?
Angular in not PHP. In order to solve this. you will need to use some service. Most popular are $http and $resource.
in case you choose $http service, you need to make
in somefile.html
in controller you will have something like this:
$scope.someFunction = function(){
$http.post(url, data, config)
.then(
function(response){
// success callback
},
function(response){
// failure callback
}
);
}
I recommend you to try to find tutorial for this like:
https://docs.angularjs.org/api/ng/service/$http
https://www.sitepoint.com/creating-crud-app-minutes-angulars-resource/
...

WebApi redirect to external site

I have a WebApi controller that after I invoke it I want it to redirect me to another site
Here is my c# code
public async Task<HttpResponseMessage> Login(LoginParameters parameters, [FromUri]string returnUrl)
{
//same validations
var response = Request.CreateResponse(HttpStatusCode.Moved);
response.Headers.Location = new Uri("Http://www.google.com");
return response;
}
My javascript code goes like this
'user strict'
var login = function ($scope, $http) {
var parameters = {
userName: userName,
password: password
};
var url = '/api/user/Login';
$http.post(url, parameters);
.then(function(response){
/*some random code that i will remove */
});
};
login.$inject = ['$scope', '$http'];
module.exports = login;
Looking at the chrome console i realise that the http POST call returns httpstatus = 302. Then i see 2 more request to requests to google.com, but my page is not redirected. So what am I doing wrong?
Thanks in advance
When you use $http, this uses an XMLHttpRequest object which does not adjust the location for the user. It will even follow redirects. You have a couple options:
You could return the new location as a field, then in the .then callback, assign window.location to cause a redirect.
You could use a standard form to post to the resource, then the browser would follow the redirects appropriately.
I would recommend you look into angular interceptors. You can "intercept" the response, check the status code, and redirect using window.location or $location. This is pretty flexible so you write the logic in one place.
Edit: this doesn't seem to work because it appears you can't catch a 302. According to this post, it appears the request is redirected automatically and the response you'd get back is from the redirected location. In the OP's post - the response was empty because the OP was redirected to a different domain which resulted in a cross-domain request (so keep this in mind if your redirects will do the same), but a proposed solution was to check the response to see if it contained data from the redirected page.

AngularJs 1.5.8: how to check if the token is valid before sending every $http (get/post) request

I am new to Angularjs and wondering how to check the token's expire date and time before sending any request.
I googled and found there are concepts like interceptors and decorators in angular but I am a bit confused which one to use and how. Or is there any better way to do it.
What am I doing right now?
I have created a service that has GET, POST functions take url, data and config as parameters and there I am checking the token. I know this is not the right approach.
You can use an interceptor that will configure every $http call. enter link description here
You can write interceptor which will cancel invalid token request before it is actually sent:
return {
'request': function(config) {
if (condition) {
var canceler = $q.defer();
config.timeout = canceler.promise;
canceler.resolve();
}
return config;
}
}
Obviously, you can manipulate config before returning it and (for example) change token.

passing data using AngularJS $http.get method

I'm building an application using the MEAN stack that would make use of data retrieved from an external API. As a measure to hide the API key, I want to make the API request from the server, however I am having problems passing the search term from the Angular front-end to the server.
The code below is part of the Angular controller, which should pass the request to the server with the search term:
myApp.controller('mainController', ['$scope','$http', '$location', function($scope, $http, $location){
$scope.submit = function(){
$location.path('/results');
$http({method: 'GET', url: '/makeSearch', data: {term: $scope.term} });
}
}]);
and then the following server code would parse the request using the body-parser middleware:
app.get('/makeSearch', function(req, res) {
console.log("I received a command!");
console.log(req.body); });
However once I try to pass/submit a search term from the front-end, I get only an empty object on the server console. Any tips on what I'm doing wrong? Any help would be appreciated.
I figured it out! #Rikky made a good point that the body of a http get request (req.body) is always empty. So by logging just the req to the console, I worked out how the search term can be sent using the GET method
Using params instead of data in the request within the AngularJS controller show in the code below:
revApp.controller('mainController', ['$scope','$http', '$location', function($scope, $http, $location){
$scope.submit = function(){
console.log($scope.term);
$location.path('/results');
$http({method: 'GET',
url: '/makeSearch',
params: {term: $scope.term}
});
} }]);
and on the server, logging req.query instead of req.body as shown in the code below:
app.get('/makeSearch', function(req, res) {
console.log("I received a command!");
console.log(req.query); });
Thanks for the help guys!
There are some http basic that you should know first, then you'll know what you are doing, then, you'll know how to do it right:
With HTTP GET method means querying for data, not sending data. Because of that, an HTTP request with GET method will not have body, so
request.body
will always be empty.
If you really want to send some data to the server, using POST is preferred.
If you still want to send data to the server via get, using query string is the best option. You can check it out at this question
If you want to send some data to the server via get method, but you don't want using query string, you can do some hack with http header instead of http body.
Make sure you have a term property in your scope.
myApp.controller('mainController', ['$scope','$http', '$location', function($scope, $http, $location){
$scope.term ='';
$scope.submit = function(){
$location.path('/results');
$http({method: 'GET', url: '/makeSearch', data: {term: $scope.term}
});
}
}]);
Make sure that your UI has an element which is bound to the term property of your scope
<input type="text" ng-model="term" />

Angular $http request in the controller does not work

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 */);

Categories

Resources