i am new in programming and angular.
i have the data like this in my controller
temanService.create({
Userid: $scope.datateman.userid,
Address: $scope.datateman.address,
Employeeid: $scope.datateman.employeeid,
Email: $scope.datateman.email,
Phoneno: $scope.datateman.phoneno,
Password: $scope.datateman.password,
Division: $scope.datateman.division,
Leavebalance: $scope.datateman.leavebalance
}).success(function(data) {
$scope.showAlert({
title: "Information",
message: "Data Telah Tersimpan"
});
});
and this is my service for http.request
angular.module('starter.services', [])
.factory('temanService', function($http) {
var baseUrl = 'http://localhost:60820/MobileBootcamp.svc/';
return {
create: function(datateman) {
return $http.post(baseUrl + 'insert?method=insertuser',
datateman, // <--- what to insert here
{
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
},
update: function(datateman) {
return $http.post(baseUrl + 'update.php', datateman, {
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8;'
}
});
},
delete: function(id) {
return $http.get(baseUrl + 'delete.php?id=' + id);
}
};
});
and this is example of the correct parameter for insert
{
"Value": "userid|address|employeeid|email|phoneno|password|division|leavebalanc"
}
My question is,
How to put data to the http request post method?
i wanted to make like this
method: 'POST',
url: 'http://110.35.82.163:9090/MobileBootcamp.svc/insert? method=insertnews',
crossDomain: true,
headers: {
'Content-Type': 'application/json; charset=utf-8'
},
data: { "Value": userID + "|" + $scope.title + "|" + $scope.posttag + "|" + $scope.content }
Try this
var data = {
Userid: $scope.datateman.userid,
Address: $scope.datateman.address,
Employeeid: $scope.datateman.employeeid,
Email: $scope.datateman.email,
Phoneno: $scope.datateman.phoneno,
Password: $scope.datateman.password,
Division: $scope.datateman.division,
Leavebalance: $scope.datateman.leavebalance
};
var dataCollection = [];
for(var item in data){
if(data.hasOwnProperty(item)){
dataCollection.push(data[item]);
}
}
var DTO = {
Value: dataCollection.join('|');
};
//do not use success. its obsolete
temanService.create(DTO).then(function(response){
},function(response){
//error
});
Writing service like this will be more readable.
create: function(datateman) {
var config = {
method: "POST",
url: baseUrl + 'insert?method=insertuser',
data: datateman,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
};
return $http(config);
}
Just add data attribute to your service.
For your code add like the following
create: function (datateman){
return $http.post(baseUrl+'insert?method=insertuser',datateman,{
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
This is the documentation
$http.post('/someUrl', data, config).then(successCallback, errorCallback);
In your code you can do
var data = { "Value": datateman.userID + "|" + $scope.title + "|" + $scope.posttag + "|" + $scope.content } + 'your next values'.
$http.post(baseUrl+'insert?method=insertuser', JSON.stringify(data) ,{
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
});
Related
For GET request the authentication working well, but when I am trying an authentication on PUT and POST requests it asks the USERNAME and PASSWORD for infinite times.
I written an authentication code for both GET and PUT but I am unable to understand why it s happening.
Please help me.
Here my GET request code:
var session_url = '';
var username = '';
var password = '';
var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.get(session_url, {}, {
headers: {
"Authorization": + basicAuth,
"Accept": "application/json",
"Content-Type": "application/json"
}
}).then((getData) => {
console.log(getData.data);
setApiData(getData.data);
}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});
Here my PUT request code:
var session_url = '';
var username = '';
var password = '';
var basicAuth = 'Basic ' + btoa(username + ':' + password);
axios.put(session_url, {}, {
headers: {
"Authorization": + basicAuth,
"Accept": "application/json",
"Content-Type": "application/json"
},
"parameters":{
"Name":name,
"Email":email
}
}).then(function(response) {
console.log('Authenticated');
alert("success");
}).catch(function(error) {
console.log('Error on Authentication');
});
"parameters" is the data in my json file.
Here my json file formate fetching from the API (This not an actual data, its just a formate of a json data)
[{"parameters":{"Name":"abc","Email":"abc#gmail.com"}}]
We have to pass body value in data parameters. Please try it.
axios.put(session_url, {}, {
headers: {
"Authorization": + basicAuth,
"Accept": "application/json",
"Content-Type": "application/json"
},
data:{
Name:name,
Email:email
},
})
for more reference check this https://stackabuse.com/how-to-make-put-http-request-with-axios/
I am very new on the forum and also with AngularJS.
I am trying to send a request to a REST server. I used this function
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/config/start';
var request = $http({
method: 'POST',
url: url,
params: {
name: 'test'
}
});
request.success(
function() {
//alert('it succeeded');
}
);
request.error(
function() {
// alert('it didnt work');
}
);
};
The code is not working properly on the server side because of some serialization stuff. I found a post on the forum that suggests using this function instead
$http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
username: $scope.userName,
password: $scope.password
}
}).success(function() {});
I am not sure how to use this function with my code, I tried this code
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/config/start';
var request = $http({
method: 'POST',
url: url,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {
name: 'test'
}
}).success(function() {});
but I get an error due to the }); . Can someone help me to format and fix the code?
$scope.submitForm = function() {
var url = 'http://localhost:8080/Server/config/start';
var request = $http({
method: 'POST',
url: url,
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
transformRequest: function(obj) {
var str = [];
for(var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
data: {name: 'test'}}).success(function () {});
} // you need a '}' here.
also you can try the post method of $http this way.
$http.post('url', data)
.success(function(data, status, headers) { //success callback })
.error(function(data, status, headers) { //error callback });
I am trying to use Angular to authenticate against an authorization endpoint that I know works using Postman.
<script type="text/javascript">
var tokenGeneratorApp = angular.module('myApp', []);
myApp.controller('AuthenticationController', function ($scope, $http) {
var ac = this;
ac.authorizationToken = null;
ac.getAuthorizationToken = function () {
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: {
grant_type: 'password',
username: 'theUserName',
password: 'thePassword'
},
headers: {
'Content-Type': 'application/json'
}
}).then(_authenticationSuccess, _authenticationError);
};
// Private methods to handle promise results
function _authenticationSuccess(response) {
ac.authorizationToken = response.data;
ac.resultsDisplay = ac.authorizationToken;
};
function _authenticationError(response) {
ac.resultsDisplay = 'An error occured: ' + response.data;
};
});
</script>
When I call getAuthorizationToken()I get an Http 400 back. When I look into the response.data object there is an error saying error:"unsupported_grant_type". This is confusing to me because in the Postman client I specify that the grant_type as password and all works as expected.
I must be doing something wrong in the Angular code.
Had a very similar problem recently. Try removing the 'headers' and insert 'dataType' instead, as follows:
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
dataType: "json",
data: {
grant_type: 'password',
username: 'theUserName',
password: 'thePassword'
}
EDIT
$http({
method : 'POST',
url: 'https://api.myserver.net/oauth/token',
data: {
"username=" + theUserName + "&password=" +
thePassword + "&grant_type=thePassword"
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
//resolving => error:"unsupported_grant_type"
vm.BtnLogin = function () {
$scope.txtUsernamee;
$scope.txtPasswordd;
var client_credentials = $scope.txtUsernamee + $scope.txtPasswordd;
var auth = 'username=' + $scope.txtUsernamee + '&' + 'password=' + $scope.txtPasswordd + '&grant_type=password';
$http({
method: "POST",
url: '/token',
contentType: 'application/json',
data: auth
}).then(function success(response) {
//$('#successModal').modal('show');
console.log("ok")
},
function error(e) {
console.log(e)
}
);
};
JS
$scope.SendData = function () {
var req = {
method: 'POST',
url: 'http://localhost:8080/ajouterPr',
headers: {
'Content-Type': 'application/json'
},
data: {'nom':$scope.nom, 'poste':$scope.poste}
}
$http(req).then(function(){
alert('success');
}, function(){
alert(error.error);
});
};
Please, can anyone tell me what's wrong with that!! Why I can't use $scope.var in my data?
Remove the $scope parameter from the SendData function. You don't need to add it as it is already available in context of the controller, and by adding it you're creating a new variable named $scope inside of SendData which is undefined because you're not passing anything in when calling it.
$scope.SendData = function () {
var req = {
method: 'POST',
url: 'http://localhost:8080/addPr',
headers: {
'Content-Type': 'application/json'
},
data: {'nom':$scope.poste, 'poste':$scope.name}
}
$http(req).then(function(){
alert('success');
}, function(){
alert(error.error);
});
};
EDIT
Try making the $scope variables into a object. You also need to make your ng-model="foo.poste" and ng-model="foo.name"
$scope.foo = {
poste : "poste",
name: "name"
}
$scope.SendData = function () {
var req = {
method: 'POST',
url: 'http://localhost:8080/addPr',
headers: {
'Content-Type': 'application/json'
},
data: {'nom':$scope.foo.poste, 'poste':$scope.foo.name}
}
$http(req).then(function(){
alert('success');
}, function(){
alert(error.error);
});
};
I need to post data to a SharePoint list, and I want to clean up my code by using
a resource factory, until now I have posted data like this:
this.save = function(data) {
data["__metadata"] = { "type": getItemTypeForListName('ListName') };
var restQueryUrl = appweburl + "/_api/lists/getByTitle('ListName')/items";
$.ajax({
url: restQueryUrl,
type: "POST",
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
},
data: JSON.stringify(data),
success: function (data) {
console.log(data);
},
error: function (error) {
alert(JSON.stringify(error));
}
});
};
And so far my resource factory looks like this:
myApp.factory('Entry', function($resource) {
return $resource(appweburl + "/_api/lists/getByTitle('ListName')/items", {}, {
get: {
method: 'GET',
headers: { "Accept": "application/json; odata=verbose" },
url: appweburl + "/_api/lists/getByTitle('ListName')/items?$select=Id,Title,Description&$filter=ID eq :ID"
},
query: {
method: 'GET',
headers: { "Accept": "application/json; odata=verbose" },
url: appweburl + "/_api/lists/getByTitle('ListName')/items?$select=Id,Title,Description"
}
})
});
How can I 'convert' my save function to a resource method?
Okey, so I was easier than I thought, what I had to do was run the function 'getItemTypeForListName' before calling the save function, this adds the metadata needed to save to sharepoint. And in my resource factory add this:
save: {
method: 'POST',
headers: {
"accept": "application/json;odata=verbose",
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"content-Type": "application/json;odata=verbose"
}
}
And then in my controller call it like this:
$scope.test = new Entry();
$scope.test.Title = 'testTitle';
// function to set metadata
$scope.test["__metadata"] = { "type": getItemTypeForListName('ListName') };
Entry.save($scope.test);