error in web api controller when getting value send from js - angularjs

i am new in angularjs i have a project where some get and post method
this is my js
var app = angular.module('angularTable', []);
app.controller('listdata', function ($scope, $http) {
$scope.joblist = function (Data) {
$scope.job = [];
$.ajax({
url: "/JobApi/getjoblist",
dataType: 'jsonp',
method: 'GET',
data: Data,
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.$apply(function () {
debugger;
if (response != null) {
$scope.divstateList = false;
$scope.divjobList = true;
$scope.job = response;
}
});
})
.error(function (error) {
alert(error);
});
}
});
And this is my web api controller
[System.Web.Http.Route("JobApi/getjoblist")]
[System.Web.Mvc.HttpPost]
public List<Getjoblist> getjoblist([FromBody]string Data)
{
try
{
JobBL objbl = new JobBL();
var joblist = objbl.Citywisejoblist(Convert.ToInt32(Data));
List<Getjoblist> list = new List<Getjoblist>();
foreach (var t in joblist)
{
Getjoblist GetAll = new Getjoblist();
GetAll.jobID = Convert.ToInt32(t.ID);
GetAll.jobtital = t.Title;
GetAll.jobdescription = t.Description;
GetAll.jobimage = t.JobImage;
list.Add(GetAll);
}
return list;
}
catch (Exception ex)
{
throw ex;
}
}
not getting the value in controller send from js how to solve the problem please help me

Related

Angularjs $http then is not working properly

I get a value of "True" in my response. How come my debugger and alert and AccessGranted() in the .then of my $http is not being invoked. Below is my Script:
app.controller("LoginController", function($scope, $http) {
$scope.btnText = "Enter";
$scope.message = "";
$scope.login = function() {
$scope.btnText = "Please wait...";
$scope.message = "We're logging you in.";
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
}).then(function (response) {
debugger;
alert(response.data);
if (response.data == "True") {
AccessGranted();
} else {
$scope.message = response.data;
$scope.btnText = "Enter";
}
},
function (error) {
$scope.message = 'Sending error: ' + error;
});
}
$scope.AccessGranted = function() {
window.location.pathname("/Home/HomeIndex");
}
});
This is in my HomeController
public ActionResult HomeIndex()
{
var am = new AuditManager();
var auditModel = new AuditModel()
{
AccountId = 0,
ActionDateTime = DateTime.Now,
ActionName = "Home",
ActionResult = "Redirected to Home"
};
am.InsertAudit(auditModel);
return View("Index");
}
Please see image for the response I get.
seems like your approach is wrong
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
Try this,
$http({
method: 'post',
url: '/Login/Login',
data: $scope.LoginUser
})
.then(function (response) {
console.log(response);
},
function (error) {
console.log(error);
});
And check your browser console for logs or any errors
Make sure the response is application/json content type, and content is json.
You can also write own httpProvider for check result from server
module.config(['$httpProvider', function ($httpProvider) {
...
I would suggest you to code like this instead of then so whenever there is success, The success part will be invoked.
$http.get('/path/').success(function (data) {
$scope.yourdata = data.data;
//console.log($scope.yourdata);
}).error(function (error){
//error part
});

400 bad request on post

Trying to send a request from my factory to the back end, getting the following error: POST http://localhost:8000/messages/58d4b22d57f49028608f7bf9 400 (Bad Request)
Factory:
app.factory('usersFactory', function ($http) {
var factory = {};
var current_user = [];
factory.login = function (data, callback) {
$http.post('/users/', data)
.then(function (response) {
current_user.push(response.data);
callback(current_user);
})
};
factory.getUser = function (callback) {
callback(current_user);
}
factory.destroy = function (callback) {
current_user = [];
callback();
}
factory.writePost = function (data) {
console.log(data);
console.log(current_user[0]._id)
$http.post('/messages/' + current_user[0]._id, data)
.then(function (response) {
$location.url('/wall');
})
}
return factory;
});
Server routes:
var wall = require('./../controllers/serverController.js')
module.exports = function(app){
app.post('/users/', function (request, response) {
wall.login(request, response);
});
app.post('/messsage/:id', function (request, response) {
wall.writeMessage(request, response);
})
}
Sever controller:
module.exports =
{
writeMessage: function (request, response) {
User.findOne({ _id: request.params.id }, function (err, user) {
var message = new Message({ message: request.body, _user: request.params.id });
message.save(function (err) {
user.messages.push(message);
user.save(function (err) {
if (err) {
response.json(err);
}
})
})
})
}
}
this is error of sever side not angular, try to check logs of server.
Also you are using Message , do have schema imported in that ?

GET call to REST API returns null

I am trying to make a GET call to test a REST API but it keeps returning null, is there anything I am doing wrong:
Making the call in controller.js
function ConsumerSearchCtrl($scope, BusinessCategoryService) {
console.log(BusinessCategoryService);
}
127.0.0.1:8000/api/category/ works perfectly fine
Code in services.js for API
/**
*
*/
function BusinessCategoryService(WenzeyAPI, $q) {
var scope = this;
scope.categories = categories;
function categories() {
var q = $q.defer();
WenzeyAPI.get('http://127.0.0.1:8000/api/category/').then(function success (res) {
q.resolve(res.data);
}, function failure (err) {
q.reject(err);
})
return q.promise;
}
}
/**
*
*/
function WenzeyAPI() {
var scope = this,
ip = "http://127.0.0.1:8000";
scope.get = get;
scope.post = post;
function get(url, data) {
data = data || {};
var req = {
method: 'GET',
url: url,
data: data
}
var q = $q.defer();
$http(req).then(function success(response) {
q.resolve(response);
}, function failure(err) {
q.reject(err);
});
return q.promise;
}
function post(url, data) {
data = data || {};
var req = {
method: 'POST',
url: url,
data: data
}
var q = $q.defer();
$http(req).then(function success(response) {
q.resolve(response);
}, function failure(err) {
q.reject(err);
});
return q.promise;
}
}
Removing WenzeyAPI and using $http resolved it.
function BusinessCategoryService($http) {
this.getAllData = function () {
return $http({
method: 'GET',
url: 'http://127.0.0.1:8000/api/category/',
});
}
}

http.post angularjs 404 error

I'm trying to post form data to a mongodb (moongose) using the angularjs http.post method and I'm getting a 404 error not sure I'm doing this correctly. It complains it cant find the url -> POST http://localhost:5000/tournaments/56bf2ea58e5ea932088ff356/games 404 (Not Found)
###### This is my api router
router.post('/tournaments/:id/games', function(req, res) {
var newGame = {};
newGame.id = req.body.id;
newGame.gameDate = req.body.gameDate;
newGame.homeTeam = req.body.homeTeam;
newGame.awayTeam = req.body.awayTeam;
newGame.homeTeamScore = req.body.homeTeamScore;
newGame.awayTeamScore = req.body.awayTeamScore;
newGame.hadOT = req.body.hadOT;
newGame.hadSO = req.body.hadSO;
Tournament.update({ "_id": req.params.id}, {$push: {games: newGame}}, function(err, model) {
if(err) {
res.send(err)
} else {
res.json(model)
}
});
});
this is in the controller
vm.isEditing = false;
vm.newGame = {
awayTeam: '',
homeTeam: '',
homeTeamScore: 0,
awayTeamScore: 0
};
vm.showModal = function() {
vm.isEditing = true;
}
vm.hideModal = function() {
vm.isEditing = false;
vm.addGameForm.$setPristine();
vm.isSaving = true;
}
vm.addGame = function() {
vm.isSaving = true;
vm.newGame.id = vm.selectedTournament.games.length + 1;
$http({
method : 'POST',
url : '/tournaments/'+tournamentId+'/games',
data : $.param($scope.vm.newGame),
headers : { 'Content-Type': 'application/x-www-form-urlencoded' }
}).success(function(response){
$scope.vm.newGame = {};
$scope.games = response;
console.log(response);
})
.error(function(data) {
console.log('Error: ' + data);
});
vm.addGameForm.$setPristine();
vm.hideModal();
}

Why does my angular/express GET work but not POST?

Here how my button's set up. The Updates.getUpdates is working. Updates.postAnUpdate returns 404
$scope.postUpdate = function () {
console.log($scope.update);
Updates.postAnUpdate($scope.update);
Updates.getUpdates().then(function (data) {
$scope.updates = data;
});
};
Here is my lovely services
app.factory('Updates', ['$http',
function ($http) {
return {
//Get the current users messages
getUpdates: function () {
return $http({
url: '/updates/',
method: 'get'
}).then(function (result) {
return result.data;
});
},
postAnUpdate: function (update) {
return $http({
url: '/updates/post',
method: 'post',
data: {
update:update,
}
}).then(function (result) {
return result.data;
});
}
};
}]);
Here's my routes to handle the urls
var updates = require('./routes/updates.js');
//Project Updates
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
And finally, here's the code that works with a 200 and console text.
exports.getAll = function (req, res) {
console.log('It worked');
}
So everything should be working for the post too, but it isn't. I'm just trying to do a console command so I know it works and I'm getting a 404
exports.newPost = function (req, res) {
var db = mongo.db,
BSON = mongo.BSON,
newPost = {};
console.log('This is giving me 404 instead of showing up in terminal');
newPost.content = req.body.update;
newPost.author = req.user._id;
newPost.date = new Date();
db.collection('updates').save(newPost, function (err, result) {
if (err) {
throw err;
}
console.log(result);
});
}
Looks as though this is a simple typographic error. in your routes:
app.get('/updates/', updates.getAll);
app.get('/updates/post', updates.newPost);
I think you want
app.post('/updates/post', updates.newPost);

Resources