My ajax doesn't call the method on the controller - ajax

I have an on my index page(thymeleaft page), with a click to call a function in ajax and this ajax method to call a method in the controller, but the method in the controller is not called.
href:
<span></span>Add
ajax:
function addproductcart(id){
$.ajax({
type : "GET",
url : "/addproductcart/"+id,
success : function(result){
$('#headsearchproduct').val(result.id);
}
});
};
controller:
#GetMapping("/addproductcart/{id}")
public ResponseEntity<Produtocarrinho> adicionarprodutocarrinho(#PathVariable("id") Long id) {
Produtocarrinho produtocarrinho = new Produtocarrinho();
Produtos produto = produtoRepository.findById(id).get();
produtocarrinho.setId(produto.getId());
produtocarrinho.setFoto1min(produto.getFoto1min());
produtocarrinho.setQuantidade("1");
produtocarrinho.setValor(produto.getPrecoNovo());
ResponseEntity<Produtocarrinho> responseEntity = new ResponseEntity<Produtocarrinho>(produtocarrinho, HttpStatus.OK);
return responseEntity;
}
I had already made a method exactly like that on another page of this project and it worked very well, and I already debugged it and saw that it is not called the controller method, does anyone know where is wrong?

I solved this, the problem was in the spring security blocking this request

Related

Asp.net Core 3.1 MVC Ajax call to method

I have this method in my controller:
public async Task<string> AjaxMethod()
{
//some codes
var jsonResults = JsonConvert.SerializeObject(results);
return jsonResults;
}
I have ajax call to this method and it works that i expected.
I realize that when i access to this method via url (like localhost:50000/Controller/AjaxMethod) it shows all data on web browser and i dont want this.
What is the best approach to prevent this issue?
additional info : i am using asp.net identity and my controller has [AutoValidateAntiforgeryToken] attribute at top.
You can change your action to post like this:
[HttpPost]
public async Task<string> AjaxMethod()
{
//some codes
var jsonResults = JsonConvert.SerializeObject(results);
return jsonResults;
}
and then in your ajax use :
type: "POST",
so that you cannot use localhost:50000 / Controller / AjaxMethod to get data in browser.

AspNetBoilerplate Ajax repose error despite 200 response code

Im having some unexpected problems with a ajax call within the aspnetboilerplate system.
I want to return an array to populate a select list,
The ajax call fires correctly and hits the controller. The controller returns the results as a model successfully, except it continually hits an error.
here is my controller action:
public async Task<List<DialectDto>> GetAllDialects(int Id)
{
var language = await _languageAppService.GetLanguage(Id);
return language.Dialects;
}
Here is my ajax call
var languageId = $(this).val();
abp.ui.setBusy('#textContainer');
$.ajax({
url: abp.appPath + 'Language/GetAllDialects?Id=' + languageId,
type: 'POST',
contentType: 'application/json',
success: function (content) {
abp.ui.clearBusy('#textContainer');
},
error: function (e) {
abp.ui.clearBusy('#textContainer');
}
});
Inspecting the return object in javascript clearly shows a 200 result with all the data in the responsetext property.
Other posts suggest that the content type isnt specified correctly and this is likely the a json parse error. Ive tried setting the dataType property to both 'json' and 'text' but still get the same response
I just had the same problem in one project. I'm using AspNet Boilerplate on a web .NET5 project.
Just like in your case I had a call to a controller method in my JavaScript code that returned 200 code, while in JS I had a parse error and then the "success" code was not executed. To solve the problem I changed the return value of my controller method. I used to return an IActionResult value (i.e. the Ok() value for ASP.NET). Then I changed the return value to another object (a DTO in my case) and everything went right afterwards. For reference:
Before (not working):
[HttpPost]
public async Task<IActionResult> Method([FromBody] YourClass input)
{
// method logic
return Ok();
}
After (working):
[HttpPost]
public async Task<DtoClass> Method([FromBody] YourClass input)
{
// method logic
return dtoClass;
}
I also tested that returning a JsonResult class works with the framework just like this (e.g. return new JsonResult(result)).
Hope this helps somebody else in the future :)

Spring ModelAndView not working with ajax call

Ajax calls a Spring Controller employee_edit but the ModelAndView is not working. It does not redirect to jsp page with object.I want to redirect to the page employee_registration.jsp with the object employee. Code has no error.
Ajax
$('#example1 tbody').on( 'click', 'button1', function () {
var eid = table.row( $(this).parents('tr') ).data().eid;
$.ajax({
type:"GET",
url:"employee_edit?eid="+eid
});
Controller
#RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public ModelAndView RegitrationEdit(#RequestParam("eid") long eid)
{
Employee employee=employeeService.getEmployee(eid);
ModelAndView mv=new ModelAndView();
mv.setViewName("employee/employee_registration");
mv.addObject("employee",employee);
return mv;
}
After running the code it does not show any error. Going through the code ModelAndView("employee/employee_registration","employee",employee); but nothing happens.
Thanks in advance.
I think in your ajax call you need to add the success parameter. You can simply modify your call as
$.ajax({
type:"GET",
url:"employee_edit",
data:{"eid":eid},
success:function(data){
}
});
or you can also add only the success parameter in your code
$.ajax({
type:"GET",
url:"employee_edit?eid="+eid
success:function(data) { }
});
But I prefer the first one. Its more clear.
This should complete the ajax call and your program should work.
When calling from ajax, ModelAndView will not work. You need to return the employee object as json by marking the the return type with annotation #ResponseBody
#RequestMapping(value="/employee_edit", method=RequestMethod.GET)
public #ResponseBody Employee RegitrationEdit(#RequestParam("eid") long eid)
{
Employee employee=employeeService.getEmployee(eid);
return employee;
}
After that upon successful call, you will get the response inside success callback.
$.ajax({
type:"GET",
url:"employee_edit?eid="+eid,
success: function(data) {
//here data is the employee object
//process it here and redirect using window.location
}
});

What is the best way to put my variable in an Ajax request function

Context: I am working on a Spring WEB MVC app using JSP for the view.
In my JSP page i have an input text field which in fact is a jquery daterange picker:
<input type="text" name="daterange" value="01/01/2017 - 01/31/2017" />
I thought in this ajax function I can retrieve the value of my input daterange and pass it to var daterange? like this:
function filterByDate() {
$.ajax({
url : 'outbatch',
data : ({}),
success : function(data) {
var daterange = document.getElementById("daterange").value();
}
});
}
And this is my Controller (i did not pase everyting it is too long don't look at the return null i just put it for showing) method who will update my batch and get the information from my model:
#RequestMapping(value = "/outbatch", method = RequestMethod.GET)
public String updateEblnotif(Model model) {
String out_path = env.getProperty("notif_out");
List<Doc> doc_list = unmarshal(out_path, "LETTERS");
System.err.println("jbb*********" + doc_list.size());
Set<String> formname_set = new HashSet<>();
`......
return null`}
My question is: Where do I have to pass the variable in my Ajax function call to my Controller? I know that, if I am not mistaken there are several other option parameters that I can pass into an Ajax function like 'data' , 'datafilter' , 'datatype' ? Which is the best way for requesting Dates assuming in my model those are Java Date Objects
Note: I am a very Junior Developer this is my first project. My model uses a DAO with hibernate to map into the database.
Thanks to all of you for your help!
first of all you should get the value of the parameter in client side so to that you simple have to add id attribute to the tag so that your getElementById could be useful, try this :
<input type="text" name="daterange" id="daterange" value="01/01/2017 - 01/31/2017" />
now let's suppose that your function is responsible on retrieving the desired value and send it as parameter to the server side with AJAX, so it's simple :
function filterByDate() {
var daterange = document.getElementById("daterange").value();
$.ajax({
url : 'outbatch',
data : {"daterange":daterange}, //here you send the daterange over an Ajax request and by default it's sended with a GET method
success : function(data) {
alert(data); //here you will see an alert displaying the callback result coming from your spring controller
}
});
}
now we sent the daterange to the controller , so we have to get it back there : to do that you simply can try the following approach :
#RequestMapping(value = "/outbatch", method = RequestMethod.GET)
public #ResponseBody String updateEblnotif(Model model,#RequestParam("daterange") String daterange) {
//so here you're ahving the daterange parameter in controller , if you want to display it in the alert , you can send it in the return like this,
String date = "the daterange is "+daterange
return date;
}
i hope it was clearly for you.

How do I cause an MVC controller to redirect the user from an ajax call?

I am sending an array as the "data" value (parameters) of an ajax call to an MVC controller. The controller should then redirect the user to a new page but it does not. Instead I can see in the Preview window that the View is being returned but through the ajax return. I am not sure if the way I am approaching this is correct because I seem to be having a hard time finding good examples to follow. I wanted to avoid an Html.ActionLink because I will have about 20 parameters to pass to the controller.
Here is the function that sends the array to the controller:
submit: function () {
var data = {
"ReqDepartment": (viewModel.reqDepartment === null) ? null : viewModel.reqDepartment,
"EquipmentGroup": (viewModel.equipmentGroup === null) ? null : viewModel.equipmentGroup,
"SiteCode": (viewModel.site === null) ? null : viewModel.site.SiteCode,
}; //header
$.ajax({
type: "POST",
url: "/ArctecLogisticsWebApp/Requisitions/ReqsSummary/",
data: data,
traditional: true
});
}
Here is the controller, ReqSearchCriteria is a ViewModel :
public ViewResult ReqsSummary(ReqSearchCriteria criteria)
{
return View("ReqsSummary", requisitionsRepository.GetReqsAdvancedSearch(criteria));
}
The controller is returning the View in the ajax call. Should I use a different approach to send an array to the controller?
ajax calls won't redirect by themselves. what you need to do is return json from the controller to the view with the result of the action and if the action is successful then redirect
$.ajax({
type: "POST",
url: "/ArctecLogisticsWebApp/Requisitions/ReqsSummary/",
data: data,
traditional: true,
success: function(result){
if(result.Success){
window.location = '#Url.Action('Action', 'Contorller')';
}
}
});
Edit:
The controller method you have will work. It should be a different name from the form you are redirecting from to eliminate confusion. Through data you can pass any information that you need.
data: { id: $('.id').val() },
something like this will pass whatever value is in the field with class id. then on your controller create the model for the view and return view. I use ajax calls everywhere, they are incredibly useful. Please let me know if you have any other questions.
You don't have to check for a result in your success/done handler and then do the redirect manually. You can actually return a JavascriptResult from your controller and it will redirect for you:
$.ajax({
type: 'post',
url: '/Home/DoStuff'
});
[HttpPost]
public ActionResult DoStuff()
{
return JavaScript(string.Format("window.location='{0}';", Url.Action("About")));
}
If you wanted to get fancy you could even create a new ActionResult type that took care of the formatting for you. Or you could detect if it is an AjaxRequest and determine if you should do a RedirectToAction or a JavaScript result.

Resources