How to post data with angular js to sql server - javascript

Thanks for all your input, but now I have more or less a similar problem, I have the data that needs to be stored in sql-server database, when I try to post it the data does not get written. Is my code structure correct?
self.CurrentDowntimeEvent = {
method: 'POST'
, url: 'someurl/test'
, data: {
DepartmentId: cookie
, CategoryId: -1
, Comment: ""
, DowntimeStart: "2014-07-07T10:00:00"
, DowntimeEnd: null
}
, headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
}).success(function (data) {
console.log(data);
}).error(function (data) {
});

$http is a service which should be injected into the controller, so you shouldn't need self. to reference it:
self.RecordsSave = function () {
for (var i = 0; i < self.Employees.length; i++) {
var employee = self.Employees[i];
var params = {
CompanyNumber: employee.ClockNumber,
Department: employee.DepartmentID,
Present: employee.Present,
Reason: employee.AbsentCode
};
$http.post(SAVE_EMPLOYEERECORDS, {
params: params
}).success(function (data) {
alert("testing");
});
}
};

Related

Passing A Single Objects Into An MVC Controller Method Using jQuery Ajax

I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name

Use loop in http post AngularJS asynchronous

I want to use foreach to get item by item and pass it to http post.
For example i want to get all chapters in lesson, i get this [”angularjs","react","ionic"], and i want to pass angularjs to get all chapters in
lessons of angualrjs .
Here is my code .
// asynchronous http
$scope.allLessons = [];
var init = function () {
var x = JSON.parse($localStorage.currentUser);
$http({
method: 'POST',
url: 'http://localhost/hrm/public/checkLs',
data: {email: x.email}
}).success(function (data) {
$scope.isRole.push(data);
console.log($scope.allLessons);
$scope.isRole.forEach(rr){
$http({
method: 'POST',
url: 'http://localhost/hrm/public/hpers',
data: {
name: rr
},
}).success(function (data) {
console.log(data);
}).error(function (data) {
console.log(data);
});
};
}).error(function (data) {
console.log(data);
});
};
init();
So in first http i get array of lessons [”angularjs","react"....]. and in second i get an error.
My backend get just name of lesson string not array, so how can i pass lesson by lesson for get the chapters of the lesson that i want ?
How and why is the best why to do it asynchronous ? and thanks.
For doing it synchronously , you can do something like below.
//post requests
var Requests = [
{
url:"your url1",
data:"your data"
},
{
url:"your url2",
data:"your data"
},
];
if (Requests.length>0) {
var exit = false;
var len = Requests.length-1;
executePost(0, Requests, len);
}
var executePost = function (i, Requests, len)
{
if (Requests[i]!=undefined && (i<=len))
{
var request = Requests[i];
var url = request.url;
var data = request.data;
$http.post(url, data, { headers: { "contentType": "application/json; charset=utf-8" } })
.then(function (success)
{
console.log("Processed " + (i + 1)); //processed log
//you can store the data to any variable here
if ((i + 1) <= len) {
executePost(i + 1, Requests, len);
}
},
function (error)
{
console.log("Unsuccessfull " + (i + 1));
});
}
}
Here the function executePost having three parameters is called recursively.
$scope.isRole.forEach(function(rr){
$http({
method: 'POST',
url: 'http://localhost/hrm/public/hpers',
data: {
name: rr
},
}).success(function (data) {
console.log(data);
}).error(function (data) {
console.log(data);
});
});
Use can use async waterfall in async.js. It is used to work on asynchronous call.
http://caolan.github.io/async/docs.html#.waterfall
async.waterfall([
function(callback) {
$http({
method: 'POST',
url: 'http://localhost/hrm/public/checkLs',
data: { email: x.email }
}).success(function(data) {
$scope.isRole.push(data);
console.log($scope.allLessons);
callback(null, isRole);
});
},
function(isRole, callback) {
// arg1 now equals 'one' and arg2 now equals 'two'
isRole.forEach(rr) {
$http({
method: 'POST',
url: 'http://localhost/hrm/public/hpers',
data: {
name: rr
},
}).success(function(data) {
console.log(data);
callback(null, data);
}).error(function(data) {
callback(err, null);
});
};
}
],
function(err, result) {
// result now equals 'done'
});

How to pass form parameters to Rest using angularjs services?

I try to pass my form parameters to java rest backend but i cant.
controller
$scope.addNewThing = function () {
Myservice.addNew($scope.name);
};
service
addNew: function (name) {
var Foo = $resource($rootScope.baseUrl + '/path/addNew', {}, {
save: {method: 'POST', params: {}}
});
var results = Foo.save({name: name}, function(data) {
results = data;
});
return results;
}
//also tried this version of code
addNew: function(name) {
return $resource($rootScope.baseUrl + '/path/addNew', {}, {
save: {method: 'POST', params: {name: 'test'}}
});
}
rest backend function
#POST
#Produces("application/json")
#Path("/addNew")
public Response addNew(#FormParam("name") String name) {
try {
//when i check name here it is always null
...
}
}
I can't pass the html form parameter to java rest backend via angular. Also tried to change #FormParam to #QueryParam but it didn't work.
Did you set the default content-type on $http POST requests?
app.config(function($httpProvider) {
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.post["Content-Type"] = "application/json; charset=utf-8";
});
I don'n know how to receive params value in java but I can show how to pass params from angular service. when you will want to pass params then you should use :paramsName in your URL path.
addNew: function(name) {
var addNewItem = $resource($rootScope.baseUrl + '/path/addNew/:name', {name: '#name'}, {
'post': {method: 'GET'}
});
return addNewItem.post({name: name});
}
or if you don't use /:name in your url you should pass in your header
addNew: function(name) {
var addNewItem = $resource($rootScope.baseUrl + '/path/addNew/:name', {}, {
'post': {method: 'GET', headers: { 'name': name }}
});
return addNewItem.post({name: name});
}
NB: your Content-Type should be application/json
You can try this:
CONTROLLER
$scope.addNewThing = function () {
yourService.addNew($scope.name);
};
SERVICE
angular.module('MyApp')
.service('yourService',['$http', function ($http) {
this.addNew = function (data) {
$http({
url: 'YourURL',
method: 'POST',
data: data, // your $scope.name
headers: {'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8'}
})
.success(function (response) {
console.log('good');
})
.error(function (response) {
console.log('error');
});
};
}]);
JAVA REST API
#POST
#Path("/addNew")
#Consumes("*/*")
public Response addNew(String name) {
// use here your String name
}
Using jQuery params solved my problem
Here is the correct way:
Myservice.addNew().save($.param({
name:$scope.name
}),function(data){
console.log(data);
},function(err){
console.log(err);
});
I can pass the parameters like this with $resource service.

Data is always null when send from view to web api controller

When I send data from my view to web api controller my ID fields are always got null in controller, below is my code
$scope.Create_Click = function (CategoryselectedItemvalue, SupplierSelectedItemvalue, Product_Name, Quantity_PerUnit, Reorder_Level, Unit_Price, Units_InStock, Units_OnOrder) {
var CategoryID = parseInt(CategoryselectedItemvalue);
var SupplierID = parseInt(SupplierSelectedItemvalue);
var ProductName;
var QuantityPerUnit;
var ReorderLevel;
var UnitPrice;
var UnitsInStock;
var UnitsOnOrder;
Product = {
CategoryID: CategoryID,
SupplierID: SupplierID,
ProductName: Product_Name,
QuantityPerUnit: Quantity_PerUnit,
ReorderLevel: Reorder_Level,
UnitPrice: Unit_Price,
UnitsInStock: Units_InStock,
UnitsOnOrder: Units_OnOrder
};
$http({
method: 'POST',
url: '/api/Products/PostProduct',
data: JSON.stringify($scope.Product),
headers: { 'Content-Type': 'application/JSON' }
}).
success(function (data) {
alert("Record Added");
}).
error(function (msg) {
alert(msg);
});
};
});
Below is my controller method (here when I recieved data CategoryID and SupplierID is always null)
[ActionName("PostProduct")]
public IHttpActionResult PostProduct(Product product)
{
Product pro = new Product();
pro.CategoryID = product.CategoryID;
pro.SupplierID = product.SupplierID;
pro.ProductName = product.ProductName;
pro.QuantityPerUnit = product.QuantityPerUnit;
pro.ReorderLevel = product.ReorderLevel;
pro.UnitPrice = product.UnitPrice;
pro.UnitsInStock = product.UnitsInStock;
pro.UnitsOnOrder = product.UnitsOnOrder;
if (repo.AddNewProduct(pro))
{
return Ok("Product Added");
}
else
{
return Ok("Error");
}
}
Since your header is 'application/json', I don't think there is any need of using JSON.stringify which basically converts json to a string and therefore, you cannot access your keys.
Just send your object as it is in JSON format.
While stringifying data it should be in JSON format, where its key would be product(action parameter name)
data: JSON.stringify({product : $scope.Product}),
Or you don't need to stringify your data if you are using Web.API, you just only need to use [FromBody] attribute before you Product parameter in action.
[ActionName("PostProduct")]
public IHttpActionResult PostProduct([FromBody] Product product)
{
//code is the same
}

Angular JS - Dynamic URL for $http get

I am trying to do a login for my app, using a rest api I designed. If I force the complete URL with the user and the pass It works alright:
http://www.myexample.com/ACTION/USER/PASSWORD/
But I need to take the data from the input fields of my form. This is code of the function in my controller:
$scope.authenticar = function(selectedUs, selectedPw){
$scope.remoteData = null;
//alert(selectedUs);
dataService.getData(function(data) {
$scope.resultAPI = data;
$scope.username=$scope.resultAPI.username;
$scope.id_user=$scope.resultAPI.id_user;
$scope.isauthenticated=$scope.resultAPI.isauthenticated;
$scope.user_role=$scope.resultAPI.user_role;
$scope.complete_name=$scope.resultAPI.complete_name;
});
}
And this is the service code:
.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(callback) {
var myparams = {a: '', u: '', p: ''};
myparams.a = 'ZW50cmFy';
myparams.u = 'anRk';
myparams.p = '899960d8dd39b29e790845912cb35d96';
$http({
method: 'GET',
url: 'http://www.adagal.net/api_adagal/api.php',
withCredentials: false,
params: myparams,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).success(function(data, status, header, config){
// With the data succesfully returned, call our callback
callback(data);
}).error(function(){
$scope.remoteData = null;
return "Connection Error";
});
}
});
I tried to pass all the ways, how can I get the URL this way?
Not entirely sure what you are trying to do here, you want to pass username and password by url? or post/get data?
Either way you'll need to pass the username and password into the service. You can do that by passing it in the service function.
this.getData = function(username, password, callback) {
...
})...
}
On the calling side:
dataService.getData($scope.username, $scope.password, function(){...});
If I understood your question correctly, you should change your service like this:
.service('dataService', function($http) {
delete $http.defaults.headers.common['X-Requested-With'];
this.getData = function(URL, callback) {
var myparams = {a: '', u: '', p: ''};
myparams.a = 'ZW50cmFy';
myparams.u = 'anRk';
myparams.p = '899960d8dd39b29e790845912cb35d96';
$http({
method: 'GET',
url: URL,
withCredentials: false,
params: myparams,
headers: {
'Content-Type': 'application/json; charset=utf-8'
}
}).success(function(data, status, header, config){
// With the data succesfully returned, call our callback
callback(data);
}).error(function(){
$scope.remoteData = null;
return "Connection Error";
});
}
});
And then call it like this:
var url = "http://wwwmyexample.com/ACTION/" + $scope.selectedUs + "/" + $scope.selectedPw + "/"
dataService.getData(url, function(data) {
$scope.resultAPI = data;
$scope.username=$scope.resultAPI.username;
$scope.id_user=$scope.resultAPI.id_user;
$scope.isauthenticated=$scope.resultAPI.isauthenticated;
$scope.user_role=$scope.resultAPI.user_role;
$scope.complete_name=$scope.resultAPI.complete_name;
});
And in HTML you should have smth like this:
<input ng-model="selectedUs" />
<input ng-model="selectedPw" />
Thank you all for the answers. I found my error:
dataService.getData(function(u, p, data) {
And here was my error
dataService.getData(u, p, function(data) {
I was putting u and p beside data, unforgivable error. Thank you all for the help.

Categories