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 &
Related
I'm trying to upload files using Angularjs for REST API exposed via Spring :
This is my Controller:
#RequestMapping(value = util/images/{partyId},
method = RequestMethod.POST)
public JsonNode uploadPartyRefImage(#RequestPart("file") MultipartFile inputFile,
#PathVariable String partyId){
ObjectMapper objectMapper = new ObjectMapper();
JsonNode jNode = null;
try {
String[] fileInput = ((DiskFileItem) ((CommonsMultipartFile) inputFile).getFileItem()).getName().split("\\.");
Path storagePath= Paths.get(uploadPath);
FileSystemUtil.writeFile(storagePath,inputFile.getInputStream());
jNode = objectMapper.readTree("{\"type\":\"" + "success" + "\",\"fileStorePath\":\"" + pathString + "\"}");
} catch (Exception exApi) {
LOGGER.error("Error uploading Party attached Image "+ exApi);
}
return jNode;
}
This API works fine when used via Postman. The Postman call:
But when calling through angular it throws Exception:
Angular service:
function uploadImage(formData,partyRefId){
console.log(utilService);
if (utilService) {
return utilService.request({
method: "POST",
resource: "/images/" + partyRefId,
headers: { 'Content-Type': undefined},
processData: false,
transformRequest: angular.identity,
mimeType: "multipart/form-data",
cache: false,
data: formData
})
.then(function (data) {
if (data) {
return getResultDataFromResponse(data);
}
}, function (error) {
console.log('error invoking document upload service', error);
});
}
}
Angular Controller:
$ctrl.uploadDocument = function () {
var formData = new FormData();
formData.append("file", k.documentfile.lfFile);
var fileName = "PARTY01" + k.documentReference;
fbeOnboardingWizardService.uploadImage(formData,fileName)
.then(function (data) {
if(data.type == "success")
console.log(data.fileStorePath);
},function (error) {
console.log(error);
});
};
Error in Jboss:
02:06:25,442 WARN [org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver] (http--0.0.0.0-8080-4) Handler execution resulted in exception: Content type 'null' not supported
If I update the Content-Type to "multipart/form-data" in angular service
Error in Jboss:
Servlet.service() for servlet appServlet threw exception: org.apache.commons.fileupload.FileUploadException: the request was rejected because no multipart boundary was found
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
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)
I'm wanting to make an ajax call from the client to the backend. I get a successful call from the success function, however, I can't understand how I get data from the server to return from the client.
currently my error trying to use res.send is:
Error: Can't set headers after they are sent.
AJAX
function getProfessorResults() {
var textData = $('#inputsm').val();
var data = {user:"gopal#gmail.com"};
$.ajax({
url: 'http://localhost:3000',
data: { theme: "somevalue", snippet: { name: "somename", content: "somevalue" } },
method: 'POST',
async: false,
cache: false,
timeout: 5000,
contentType: "application/json",
success: function(data) {
console.log("success");
},
complete: function(data) {
console.log("completed");
},
error: function(jqXHR, textStatus, errorThrown) {
alert('Error connecting to the Node.js server... ' + textStatus + " " + errorThrown);
}
});
}
JS Backend
exports.home = function(req, res) {
function passList(profArray, callback) {
setTimeout(function () {
callback(profArray);
}, 1000);
}
function getProfs(teacher_name, successCallback) {
google.resultsPerPage = 10
var nextCounter = 0
google(teacher_name, function (err, res){
if (err) console.error(err)
var teacher_results = []; //Hold all the teachers returned from the function
for (var i = 0; i < res.links.length; ++i) {
var link = res.links[i];
if (!link.title.includes('Add') || !link.title.includes('RATINGS') || !link.title.includes("Hint")) {
teacher_results.push(link.title);
}//End if for comparisons ||
} //End For
successCallback(teacher_results);
}); //End google function
teacher_results = ['tester1', 'tester2'];
successCallback(teacher_results);
} //End searchForProfessor
getProfs(teacher_name, function(data) {
prof_list = data;
console.log(prof_list);
return true;
});
if (req.method == 'POST'){
console.log("true");
// dataReceived = JSON.parse(req);
// console.log(dataReceived);
var obj = {
tid: 'ryan'
};
res.send(JSON.stringify(obj));
}
res.render('home', {
profs: prof_list,
dataStuff : dataReceived
});
};
In the backend, you should have some route where your AJAX call lands. In there, you can invoke send on your response.
In node.js/express, this would look something like
app.get('/ajaxURL', function (req, res) {
res.send('I want this string to return to the client');
});
To access the data from the frontend, access it in your AJAX callback:
$.ajax({url: '/ajaxURL'}).done(function (data) {
console.log(data);
});
I am not getting the context properly but you can figure out by this example .
Sending data from server
response.send("Your data");
Access this data in your client in success method of AJAX:
success:function(data){console.log(data)};
I have following tutorial how to request value from node js and return back to user requested but not successful.
here my javascript code..
put('id','coment',function(data) {
var obja = JSON.parse(data);
var items = Object.keys(obja);
items.forEach(function(item) {
alert(obja[item].field1); //its no result value
});
})
function put(id, data, callback) { //call from here to nodejs
$.ajax('http://localhost:8000/' + id + '/', {
type: 'POST',
data: JSON.stringify(data),
dataType: 'json',
success: function(data) { if ( callback ) callback(data); },
error : function() { if ( callback ) callback(false); }
});
}
and here my nodejs
connection.query("SELECT field1,field2,field3 from table", function(e, row) {
if(e)
{
console.log('An error occured: '+e)
}
else
{
try{
res.write(JSON.stringify(row)); //send value back to user requested
res.end();
}catch(ex){
console.log('errror' + ex) ;
}
}
});
in console, the query was load normally but when I try send back to user requested, it gets no value.
My problem is, why can't I send back to user requested?
You shouldn't need var obja = JSON.parse(data); because it will already be parsed by jQuery due dataType: 'json' being set.
Also based on the code you've shown obja is an Array so instead of this:
var items = Object.keys(obja);
items.forEach(function(item) {
alert(obja[item].field1);
});
Just do this:
obja.forEach(function(row){
alert(row.field1);
});