I would like to register new users in an asp.net application. Instead of using a form I would like to use Ajax.
This is my post function in my AccountController:
[System.Web.Mvc.HttpPost]
public async Task<bool> Register(UserItem post) {
try {
var user = new ApplicationUser { UserName = post.UserName, Email = post.UserName };
var result = await UserManager.CreateAsync(user, post.Password);
if (result.Succeeded) {
post.Id = user.Id;
await _userRepository.Save(post);
return true;
}
AddErrors(result);
}
catch (Exception e) {
Console.WriteLine(e);
}
// If we got this far, something failed, redisplay form
return false;
}
And this is my Ajax call to my controller:
var userJson = ko.toJSON(self.selectedUser);
console.log(userJson);
$.ajax({
type: "POST",
url: "http://localhost:7061/Account/Register",
headers: "application/json; charset=UTF-8",
dataType: "json",
contentType: "application/json",
data: userJson,
error: function (xmlHttpRequest, textStatus, errorThrown, response) {
},
success: function (response) {
console.log(response);
self.loadUsers();
}
});
But my register function in the controller never gets called.
Thanks.
On AccountController every action needs to return an ActionResult object, or in the case of an async action, a Task<ActionResult>. Otherwise, it won't be seen as an action, and no request will be routed to it.
Change the signature of the method to:
public async Task<ActionResult> Register(UserItem post) {
and instead of returning true or false, return Json(true) or Json(false)
Related
I am doing a simple function to update a field in the database and I get this error:
Failed to load resource: the server responded with a status of 403 (Forbidden)
I do the request in html/Jquery:
function AgregarLike(id, num){
alert("Entre:" + id);
var urlAction = "#Url.Action("UpdateLikeVisitBrandPhoto", "Report")";
alert (urlAction);
var request;
// Fire off the request to /form.php
request = $.ajax({
url: urlAction + '/' + id,
type: "post"
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
console.log(response);
console.log(textStatus)
alert("worked");
});
}
And the controller (I return all the time bu.CreateLike(Id) because I want to forze the error):
public int UpdateLikeVisitBrandPhoto(int id)
{
try
{
try
{
var num = bu.CreateLike(id);
}
catch
{
return bu.CreateLike(id);
}
return bu.CreateLike(id);
}
catch (ServicesException ex)
{
logger.Error("", ex);
Console.WriteLine(ex);
return bu.CreateLike(id);
}
catch (Exception ex)
{
logger.Error("", ex);
Console.WriteLine(ex);
return bu.CreateLike(id);
}
}
And the model:
public int CreateLike(int id)
{
using (var sqlConnection = DatabaseUtilities.GetConnection())
{
var SQL = "UPDATE [RBAcuerdos].[dbo].[VisitBrandPhoto] SET MeGusta = 1 WHERE id = #paramId";
var sqlCommand = new SqlCommand(SQL, sqlConnection);
sqlCommand.Parameters.Add(new SqlParameter("paramId", id));
//sqlCommand.Parameters.Add(new SqlParameter("paramvalue", 1));
return sqlCommand.ExecuteNonQuery();
}
//throw new NotImplementedException();
}
Someone can help me please?
Since you're sending a POST request, the parameters you need to send should not be a part of the URL. Try sending the parameters like:
request = $.ajax({
url: urlAction,
data: {id: id},
type: "POST",
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("It worked!");
},
error: function () {
alert("Error");
}
});
Further Reading:
How to pass parameters in $ajax POST?
request = $.ajax({
url: urlAction + '?id=' + id,
type: "get"
});
Substitute your code
var urlAction = "#Url.Action("UpdateLikeVisitBrandPhoto", "Report")";
It generates
/Report/UpdateLikeVisitBrandPhoto
To hit controller you need your url to be
/Controller/Action?param1=paramvalue //single param
/Controller/Action?param1=paramvalue ¶m2=paramvalue //multiple params,apppend each paramname with prefix &
In server side,I fetch data from database
var sql = require('mssql');
app.get('/api/comments', function(request, response) {
var sqlConfig = {
// Connection string parameters.
}
sql.connect(sqlConfig, function() {
var request = new sql.Request();
var stringRequest = 'select TOP 10 * from comment';
request.query(stringRequest, function(err, recordset) {
if(err) console.log(err);
sql.close();
response.json(recordset);
});
});
});
Then,I fetch the data from server side by AJAX (get method)
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
success: (comments) => {
this.setState({ comments })
}
});
I get an error when I get the data by Ajax.
(Uncaught TypeError: this.state.comments.map is not a function)
It seems that the data return is undefined.Instead of fetching database,the code is work if I use static data(hard code) in server side.
I think the problem is the callback function in sql.connect() but I have no idea how to solve it.Does anyone can help?
Error:
The solution is adding dataType: 'json' to the ajax
_fetchComments() {
jQuery.ajax({
method: 'GET',
url: '/api/comments',
dataType: 'json',
success: (comments) => {
this.setState({ comments })
}
});
}
I make a POST AJAX request:
firebaseAUTH.currentUser.getToken(true).then(function(idToken) {
$.ajax({
// Send token to your backend via HTTPS (JWT)
url: '/auth',
type: 'POST',
data: {token: idToken},
success: function (response) {
var userID = response.userID
firebaseDB.ref('/users/' + userID)
.once('value')
.then(function(snapshot) {
$.post('/members-area/' + userID, snapshot.val(), function(data, status) {
});
});
}
});
});
My handler:
app.use('/members-area/', function(req,res,next) {
console.log(req.body) //works well and gives object
res.render('members-area', { Snapshot: req.body})
})
However, it does not render the page. Why is that and how can I achieve that?
I can't move that function call outside of the success attribute of the AJAX call, as then the decoded userID variable would not be available.
I have a REST API running and I am posting some data to it using JQuery.
This is how my JQuery code looks:
$(document).ready(function () {
$('#login-form').submit(function () {
var user = $('#uname').val();
var pass = $('#pwd').val();
alert('username = ' + user);
alert('password = ' + pass);
var JSONObject = { 'userName': user, 'password': pass };
var jsonData = JSON.parse(JSONObject);
$.ajax({
url: 'http://127.0.0.1:8080/user/login',
method: 'POST',
data: { userName: user, password: pass },
dataType: 'JSON',
contentType: 'application/json',
success: function (data, status, jqXHR) {
//Do something
console.log('data = ' + data);
},
error: function (jqXHR, status, errorThrown) {
alert('error ' + errorThrown);
}
});
});
});
However, this code is unable to access the API. I do not get the expected message in the server log.
When the Submit button of the form is clicked, the browser gets reloaded and it shows the form inputs in the url. That is all.
My API is written using Java and this is the relevant method.
#RequestMapping(value = "/user/login", method = RequestMethod.POST)
public ResponseEntity<User> logUser(#RequestBody User user){
User loggedUser = loginService.authenticateUser(user);
if(loggedUser != null){
System.out.println("User found");
return new ResponseEntity<User>(loggedUser, HttpStatus.ACCEPTED);
}else{
//user does not exsits
System.out.println("User not found");
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
}
I really can't understand what is wrong. No any error is shown. Can somebody point me out why this happens and how to fix this issue.
The issue is that the browser is reloading on submit event.
You need to add preventDefault() method like this
$("#login-form").submit(function (event) {
event.preventDefault()
//further code here
This will prevent the browser from reloading
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");
});