without the parameters of the method Get, the code works, but if the method asks for a parameter an error 404 is returned. How do I properly send parameters with Angular JS?
factory.test = function () {
var q = $q.defer();
$http({
method: "GET",
url: url + "/dataEntry/test",
data: {
sampletext : "sample"
}
})
.success(function (data, status, headers, config) {
q.resolve(data);
})
.error(function (data, status, headers, config) {
q.reject(data);
});
return q.promise;
};
[Route("test")]
public String Get(string sampletext)
{
return "Reply coming from data entry controller" + sampletext;
}
Since it's a GET request you shouldn't be sending data. You need to be sending a query string.
Change your data to params.
$http({
method: "GET",
url: url + "/dataEntry/test",
params: {
sampletext : "sample"
}
})
Source: http://docs.angularjs.org/api/ng/service/$http
$http({
url: "/saveInfo",
method: 'Post'
}).then(function(response) {
console.log("saved successfully");
}, function(response) {
console.log("Error message");
});
Related
I have a simple login, once user is logged in I have added a call back to run another post so that I have access to the post json to use in my system.
I think the way I have done it is correct however I am getting error
GetData is not defined
Is this the correct way to do this
JavaScript
$scope.LogIn = function () {
$http({
url: "http://www.somesite.co.uk/ccuploader/users/login",
method: "POST",
data: $.param({'username': $scope.UserName, 'password': $scope.PassWord}),
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
GetData();
// location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
$scope.UserData = function ($scope) {
$scope.UserName = "";
$scope.PassWord = "";
};
$scope.GetData = function () {
$http({
url: " http://www.somesite.co.uk/ccuploader/campaigns/getCampaign",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (response) {
// success
console.log('you have received the data ');
console.log("then : " + JSON.stringify(response));
location.href = '/cms/index.html';
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
You need to update your code to be $scope.GetData();.
Currently you are using GetData() which doesn't reference the same method. In fact it is undefined as per the error message.
I was trying a lot of aproaches, some of them:
$http({
method: 'GET',
url: '/Url'}).then(function successCallback(response) {
}, function errorCallback(response) {
});
var req = {
method: 'GET',
interceptor: {
response: function (response) {
console.log(response)
var result = response.resource;
result.$status = response.status;
return result;
}
},
url: url,
headers: {
'Authorization': token
}
}
$http(req).success(function (data, status, headers, config) {
console.log(data, status, headers, config);
}).error(function (data, status, headers, config) {
console.log(data, status, headers, config);
});
And a lot of others with no result, so I really need help !!!
I would grateful for any help
The first approach looks close to what you need.
function successCallback(response) {
console.log('status code: ', response.status);
}
Currently the callback is empty so we are accessing response object and logging status code from it.
The first way is the more direct way of doing but I'm pretty sure that the response functions should be anonymous. Putting a console.log() in both will help.
$http({
method: 'GET',
url: '/Url'
}).then(function(response) {
console.log(response.status);
}, function(response) {
console.log(response.status);
});
If that doesn't work just put the console.log(response) in both to see what it gets you.
You can use httpinterceptor if you want to track all your requests :
myModule.factory('myHttpInterceptor', function ($q) {
return {
response: function (response) {
// do something with success response
// status in response.status
return response;
},
responseError: function (response) {
// do something with error response
// status in response.status
return $q.reject(response);
}
};
});
myModule.config(function ($httpProvider) {
$httpProvider.interceptors.push('myHttpInterceptor');
});
my question is: How can i pass variable(java script) to a rest apllication
This one of my functions in my controller.js:
This code sampel work, but i cant use my var email and password.
at the moment i use the url path log me in(url : 'rest/ab/einloggen/t#rt.de/22'). But how can i use var email(t#rt.de) and passwort(22).
app.controller('loginCtrl', function($scope, $location,$http){
$scope.submit = function(){
var email = $scope.username;
var password = $scope.password;
$http({
method : 'GET',
url : 'rest/ab/einloggen/t#rt.de/22'
}).success(function(data, status, headers, config) {
console.log(data);
if(data=="true"){
$location.path('/eingeloggt');
console.log("lalala");
}
}).error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
};
});
Here is the login rest function:
#Path("/einloggen/{username}/{passwort}")
#GET
public String einloggen(#PathParam("username") String Username,#PathParam("passwort") String Passwort)
{
// Bekomme die strings
Business b = new Business();
boolean test =b.einloggen(Username, Passwort);
//Return einer JSON
String ersatzBool ="false";
if(test==true){
ersatzBool="true";
}
return ersatzBool;
}
if you want to pass data to webapi you can use
'POST' instead of 'GET', In the below example I have passed json data {id: 2 }
and getting response as a list of products, In the api post method id 2 is available.
$http.post('http://localhost:1011/productDetails', { Id: 12 }, {
headers: {
'Content-MD5': '917200022538',
'Accept': 'application/Json',
'Content-Type': 'application/Json'
}
}).then(onUserComplete, onError);
var onUserComplete = function (response) {
$scope.Products = response.data;
};
var onError = function (reason) {
$scope.error = "Error while fetching records.";
};
This is something I had to do while communicating with a server(CMS application - Contentstack) using Restful api's, one striking difference would be I had to use authtoken.
$http({
url: siteUrl,
method: methode,
headers: {
access_token: auth_token,
api_key: site_api_key,
Accept: data_type, // --> 'application/json, text/plain, */*'
},
data: dataBody
}).then(function (resp) {
console.log('success ', resp);
callback(resp);
}, function(err){
console.log(err, "error");
});
My code is like this
$http.post("../services/myurl.aspx?Param=" + finaldata, '', { 'Content-type': 'text' })
.success(function (pricedata) {
alert (success)
})
.error(function () {
alert('we have failed to make a connection with the server. Please try after some time');
});
When I make this call neither success nor error happens.But the service is called. I am a little confused. can anyone point out what I am doing wrong?
You should use service to post data, here is how you could do it.
doSomething: function (data, url) {
return $http({
url: url,
method: 'POST',
data: data
});
},
and in your controller consume this service as
someService.doSomething($scope.MyData, $scope.Url)
.success(function (response) {
console.log("Success", response);
})
.error(function (data, status, headers, config) {
console.log("Error");
});
Try this simple code....
$http({
method: 'POST',
url: "../services/myurl.aspx?Param=" + finaldata,
})
.success(function (data, status, headers, config) {
var success="success"
alert (success);// or alert("success")
})
.error(function (data, status, headers, config) {
alert('we have failed to make a connection with server. Please try after some time');
});
In my single page Angular app I have a controller, which makes calls to a data service.
In the data service the results are being pushed onto an array named _result.
On any subsequent calls to the data service, the _result array is being appended to, instead of being emptied out first, which results in a duplicate data being passed to the controller and displayed in a view.
I am very new to Javascript, and asking for help to ensure that any additional calls to data service only return unique data.
Here is my controller:
angular.module('frontEndApp').controller('ViewExistingRequestsCtrl', ['$scope', 'requestsRepository',
function ($scope, requestsRepository) {
$scope.sendrequest = requestsRepository.getServiceRequests();
$scope.requests = requestsRepository.result;
}]
);
And here is my data service, which has the _result array:
frontEndApp.factory('requestsRepository',function ($http) {
var _result = [];
var postServiceRequest = function (ServiceRequest) {
$http(
{
url: 'http://localhost:8080/api/ServiceRequests', method: "POST", data: ServiceRequest,
headers: {
'Content-Type': 'application/json'
}
}).success(function (data, status, headers, config) {
console.log("postServiceRequest Status: " + status);
}).error(function (data, status, headers, config) {
console.log("postServiceRequest FAILURE: " + status + " ServiceRequest: " + ServiceRequest);
});
};
var getServiceRequests = function () {
$http({
method: 'GET', url: 'http://localhost:8080/api/ServiceRequests'
}).success(function (data, status, headers, config) {
for (var key in data) {
_result.push(data[key]);
} console.log(_result)
return _result;
}).error(function (data, status, headers, config) {
return status;
});
};
return {
postServiceRequest: postServiceRequest, getServiceRequests: getServiceRequests, result: _result
};
});
Just redefine it as an empty array before populating it:
...
$http({
method: 'GET', url: 'http://localhost:8080/api/ServiceRequests'
}).success(function (data, status, headers, config) {
_result = []; // <---- this is the key!
for (var key in data) {
_result.push(data[key]);
...