Spring Boot + Bootstrap + jQuery : Error 404 in $ajax call on Firefox - javascript

I've an application using Spring Boot + Bootstrap + Thymeleaf. I am trying to make an AJAX call to fill a combox use the jquery. In the Chrome workes well. In the Firefox gives me the 404 message. What could be happend?
The Firefox console.log message:
enter image description here
My AJAX code:
function carregaComboAtivoAjax(url) {
var Id = document.getElementById('idUo').value;
$.ajax({
url: url,
dataType: 'html',
data: { Id: Id },
success: function(data) {
if (data != null) {
$("body").html(data);
}
}
});
}
My Controller Code:
#RequestMapping(value = "/carregaComboAtivoCadastraCampo", method = RequestMethod.GET)
private String carregaComboAtivo(#RequestParam UUID Id, Model model) {
...
}
Best,

If you have the same problem, that is the solution:
In the spring boot controller method you need write like this:
#RequestMapping(value = "/carregaComboAtivoCadastraCampo", method = RequestMethod.GET, produces = { MediaType.TEXT_HTML_VALUE })
#ResponseBody
public ModelAndView carregaComboAtivo(#RequestParam UUID uoId, Model model) {
...
}
You need to set the media type produces.

Related

How to post js string to C# in ASP.NET Core MVC

I am new to ASP and I am trying to take a string in my JS code and post it to my controller so that I can use it to query my database.
JavaScript
function findEmployees(userCounty) {
$.ajax({
type: "POST",
dataType: "json",
url: '#Url.Action("Index", "Contact")',
data: JSON.stringify(userCounty),
contentType: "application/json",
success: function (response) {
alert(userCounty);
},
error: function (response) {
alert("failed");
}
});
}
Controller
[HttpPost]
public ActionResult Index (string userCounty)
{
var query = //use linq to query database
return View(query);
}
I only ever get the "success" alert when I use a JsonResult function in my Controller but I need it to eventually return a LINQ query to the View(); function and that hasn't worked when using a JsonResult function. Any ideas would be helpful. I don't necessarily have to use ajax if there is a better way. I just need a way to pass the string stored in userCounty to my controller.
Please change your controller method like this
[HttpPost]
public ActionResult Index([FromBody]string userCounty)
{
var query = //use linq to query database
return View(query);
}
For viewing the page, you'll need
[HttpGet]
public ActionResult Index()
{
return View();
}

POST call not working for webapi

I am trying to post data in webapi for some operations . My web api contains multiple POST method.When I post data using postman it's hit to the controller method but data is passed as null.When i hit same method from web application it does not work and shows 404 error,
POST Call :
var urlstring = "/api/Membership/BulkUpload"
$.post(
urlstring,
JSON.stringify(exceljson)).
success(function(data)
{
console.log(data);
}
);
Controller Method:
[HttpRoute("api/Membership/BulkUpload")]
public HttpResponseMessage BulkUpload([FromBody]string studentDetails)
{
Some Code Here
}
when i remove [FromBody] then it does not hit from postman too. I am not getting what going wrong in post call
Try the following code,
var urlstring = "/api/Membership/BulkUpload"
$.post(
urlstring,
{JSON.stringify(exceljson))})
.done(function(data)
{
console.log(data);
}
);
You could try one of the following:
1 - Without [From Body]
Client Side
var urlstring = `/api/Membership/BulkUpload?studentDetails=${value}`
$.post(
urlstring,
{}).
success(function(data)
{
console.log(data);
}
);
[HttpRoute("api/Membership/BulkUpload")]
public HttpResponseMessage BulkUpload(string studentDetails)
{
Some Code Here
}
2 - MAP to C# object
Client Side
var urlstring = '/api/Membership/BulkUpload'
$.post(
urlstring,
{
studentDetails : value
}).
success(function(data)
{
console.log(data);
}
);
Server Side
[HttpRoute("api/Membership/BulkUpload")]
public HttpResponseMessage BulkUpload([FromBody]studentApiModel dataIn)
{
Some Code Here
}
public class studentApiModel
{
public string studentDetails { get; set; }
}

How to call a cs function in another library with ajax

Im working with the model view/Controller, so im trying to keep files in different folders like this
Im trying to call a c# class on the Business folder from the Boleta proyect with ajax within a aspx like this.
$.ajax({
type: "POST",
url: "Business/SaveExpenses.cs/save",
data: JSON.stringify({ questions: questions}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
alert(data);
console.log(data);
},
error: function (data) {
alert("fail");
}
});
The c# file that im trying to call looks like this.
namespace Business
{
public class SaveExpenses
{
public string save(string foo)
{
string ret= "something";
return ret;
}
}
}
When the page is executed and goes through the ajax function it throws an error 404 not found.
Now my question is, how do I navigate the folders in asp.net? or the correct way of calling the function.
Im comming from a php environment and im pretty new to asp.net so i will gladly take any suggestions
This url is wrong:
url: "Business/SaveExpenses.cs/save"
The URL should refer to the actual route. For example:
public class BusinessController : Controller
{
// GET
public ActionResult Index()
{
return View();
}
public string Save()
{
string ret= "something";
return ret;
}
Then your URL would be Business/Save(subject to RouteConfig etc considerations).
In Boleta project add the namespace of business
using Business;
then create one action in controller into Boleta Project
public JsonResult Save(param)
{
SaveExpenses se = new SaveExpenses();
var result= se.Save(param);
return json(result);
}
and call save() action through ajax
look into Adding a Web API Controller. basically, your ajax call will hit a http endpoint in which you'll execute your server side logic there.
The following is just a generic pattern - you'll need to implement a bit more plumbing to get this functional...
$.ajax({
type: 'POST',
url: '/Business/Expenses', // http route
// [...]
});
[RoutePrefix("Business")]
public class ExpensesController : ApiController
{
[HttpPost]
public IHttpActionResult Save([FromBody] string questions)
{
// do stuff
return Ok("something");
}
}

Ajax post request in Spring MVC

I am currently trying to call an ajax request from a JavaScript onchange handler to call a Spring MVC controller. I believe the way I am currently calling the URL in my view is wrong since I get an 404 error on the browser when the event is triggered and call for url. Can anyone shine some light if I have everything setup correctly?
Here is my code:
#Controller
public class DataTableController
{
#RequestMapping(value = "/table", method = RequestMethod.GET)
public String home(Model model) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> gpnList = new ArrayList<GPN>();
gpnList.add("GPN-1"); gpnList.add("GPN-2"); gpnList.add("GPN-3");
model.addAttribute("gpnList", mapper.writeValueAsString(gpnList));
return "index"; //name of my view
}
#RequestMapping(value = "/getsector", method = RequestMethod.POST)
public #ResponseBody String getSector(#RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(sectors);
}
}
Jquery Code:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
var filters = { "market" : market }
filters = JSON.stringify(filters);
$.ajax({
url: "/getsector",
type: "POST",
dataType : 'json',
contentType : "application/json",
data: JSON.stringify(filters),
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
The main thing I want to achieve is being able to call my controllers via ajax calls. Any other tips on Spring Controller Mapping and conventions will be appreciated.
If your a requesting information you should use GET requests, not POST.
You are mixing #RequestParam with a json payload. If you want to receive your filter as a request param it has to go at the url, not as a json payload, using something like:
$(document).ready(function()
{
document.getElementById("markets").onchange = function()
{
var market = $("select[id='markets'").find('option:selected').text();
$.ajax({
url: "/getsector?market="+market,
type: "GET",
success: function(response)
{
console.log("sucess!");
},
error: function(e){
console.log("ERROR: ", e);
}
});
}
});
#RequestMapping(value = "/getsector", method = RequestMethod.GET)
public #ResponseBody String getSector(#RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException
{
.... your logic.
}
On the other hand, if you really want to use POST requests with a json payload, you need to use #RequestBody at the controller and bind the json object to a bean with the same properties.
#RequestMapping(value = "/getsector", method = RequestMethod.POST)
public #ResponseBody String getSector(#RequestBody Market market) throws JsonGenerationException, JsonMappingException, IOException
{
List<String> sectors = new ArrayList<String>();
sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog");
return sectors;
}
public class Market
{
String market;
//getter and setter...
}
Bear in mind your javascript is wrong as well, you are using JSON.stringify twice.
If you use #ResponseBody and spring is configured fine it will make the serialisation for you when returning the response, so you do not have to do it manually.
This code has not been tested, it is just for you to get an idea.

Pass array data from javascript in browser to spring mvc controller using ajax

I would like to pass an array from javascript in web browser to a Spring MVC controller using AJAX
In javascript, I have
var a = [];
a[0] = 1;
a[1] = 2;
a[2] = 3;
// how about multiple arrays as well?
$.ajax({
type : "POST",
url : "/myurl",
data : //not sure how to write this, ("a="+a), ?
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
In Java, I would like to create a class to receive data from AJAX, and I create a class to receive data
package com.amazon.infratool.ui;
import lombok.Getter;
import lombok.Setter;
#Setter #Getter
public class RepairInfomationParameters {
//how to write this variable?
List<String> a = null; // is it something like this?
}
What is the correct way to do this? Thanks!
You can do this from the JavaScript side:
$.ajax({
type : "POST",
url : "/myurl",
data : {
myArray: a //notice that "myArray" matches the value for #RequestParam
//on the Java side
},
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
Then on the Java side (in Spring 3), assuming that this method is mapped by /myurl:
public String controllerMethod(#RequestParam(value="myArray[]") Integer[] myArray){
....
}
I believe the following will also work:
public String controllerMethod(#RequestParam(value="myArray[]") List<Integer> myArray){
....
}
Spring is smart enough to figure out how to do the binding.
For multiple arrays, you might want to just have a command object:
public class MyData {
private List<Integer> firstArray;
private List<Integer> secondArray;
private List<Integer> thirdArray;
...
...
}
Then on the JavaScript side:
$.ajax({
type : "POST",
url : "/myurl",
data : {
myData: {
"firstArray": firstArray,
"secondArray": secondArray,
"thirdArray": thirdArray
}
},
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
On the Java side, you can bind using #ModelAttribute:
public String controllerMethod(#ModelAttribute(value="myData") MyData myData) throws ParseException {
....
}
EDIT
Changed the #RequestParam annotation to use myArray[] instead of just myArray, since this change appears to have been made in Spring after this answer was first posted.
It is very simple passing such data to the Spring MVC controller, when you have in mind that data is being parsed from string. So if you want to get an array/list in the controller - pass a stringified version of the array:
public String method(
#RequestParam(value = "stringParam") String stringParam,
#RequestParam(value = "arrayParam") List<String> arrayParam) {
...
}
and the corresponding javascript with jQuery would be like:
$.post("/urlToControllerMethod",
{
"stringParam" : "test",
"arrayParam" : [1, 2, 3, "test"].toString()
}
);
Note: the parameter type
List<String> arrayParam
could be as well replaced with the array equivalent
String[] arrayParam
Vivin Paliath doesn't work unless you use myArray[]
public String controllerMethod(#RequestParam(value="myArray[]") Integer[] myArray){
...
}
If you are using spring mvc 4 then below will be the best approach
Jquery code
var dataArrayToSend = [];
dataArrayToSend.push("a");
dataArrayToSend.push("b");
dataArrayToSend.push("c");
// ajax code
$.ajax({
contentType: "application/json",
type: "POST",
data: JSON.stringify(dataArrayToSend),
url: "/appUrl",
success: function(data) {
console.log('done');
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error while post');
}
});
Spring controller code
#RequestMapping(value = "/appUrl", method = RequestMethod.POST)
public #ResponseBody
void yourMethod(#RequestBody String[] dataArrayToSend) {
for (String data : dataArrayToSend) {
System.out.println("Your Data =>" + data);
}
}
check this helps you or not!
Cheers!
Fully tested solution
$.ajax({
type : "POST",
url : "/myurl",
data : {
myArray: a //notice that "myArray" matches the value for #RequestParam
//on the Java side
},
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
#RequestMapping(value = "/save/", method = RequestMethod.POST)
public String controllerMethod(#RequestParam(value="myArray[]") List<Integer> myArray){
System.out.println("My Array"+myArray.get(0));
return "";
}
I end up doing this and it works
In js,
var a = [];
a[0] = 1;
a[1] = 2;
a[2] = 3;
$.ajax({
type : "POST",
url : "/myurl",
data : "a="+a, //multiple array, just add something like "&b="+b ...
success : function(response) {
// do something ...
},
error : function(e) {
alert('Error: ' + e);
}
});
java side, get a class to receive data, using lombok
#Setter #Getter
public class MyData {
private ArrayList a;
}
then in the controller
#RequestMapping(value = "/repair_info", method = RequestMethod.POST)
public ModelAndView myControl(MyData myData) {
// get data with myData object
}

Categories