i want to get a value through ajax call this is how i have done,
<input type="text" id="CIMtrek_CI_CER" name="CIMtrek_CI_CER" onblur="getProjectInfo()"/>
and this is what is my script,
function getProjectInfo(){
var cerNo = document.getElementById('CIMtrek_CI_CER').value;
$.ajax({
type: "POST",
url: "CIMtrek_Project_Information",
data: {
cerNo: cerNo
},
success: function (msg) {
alert("msg : "+msg);
document.getElementById('div_CIMtrek_CI_Used_By_ProjNo').innerHTML=msg;
}
});
}
and this is what is my spring method :
#RequestMapping(value = "/CIMtrek_Project_Information", method = RequestMethod.POST)
public String getProjectInfotmation(#RequestParam("cerNo") String cerNo,HttpServletRequest request,HttpServletResponse response) throws Exception {
System.out.println("cerNo : "+cerNo);
return cerNo;
}
controll goes to this method and prints the value also but it does not replicate in call back where i have assigned the value.
success: function (msg) {
alert("msg : "+msg);
document.getElementById('div_CIMtrek_CI_Used_By_ProjNo').innerHTML=msg;
}
when i have used firebug the response is HTTP Status 404 - /ProjectCapexMonitoring/WEB-INF/views/81723.jsp
81723 is the input i gave with this input .jsp is added and gives this exception.
Please help me to fine what is the and resolve.
Best Regards.
If you are expecting json response and
have jackson jars in your classpath
add #ResponseBody to your method
change
#RequestMapping(value = "/CIMtrek_Project_Information", method = RequestMethod.POST)
public String getProjectInfotmation(#RequestParam("cerNo") String cerNo,HttpServletRequest request,HttpServletResponse response) throws Exception {
System.out.println("cerNo : "+cerNo);
return cerNo;
}
to
#RequestMapping(value = "/CIMtrek_Project_Information", method = RequestMethod.POST)
public #ResponseBody String getProjectInfotmation(#RequestParam("cerNo") String cerNo,HttpServletRequest request,HttpServletResponse response) throws Exception {
System.out.println("cerNo : "+cerNo);
return cerNo;
}
Related
I'm having error when creating an object in javascript
I'm having this generic error:
Uncaught SyntaxError: Invalid or unexpected token
That's why i can't solve it. it didn't have specific error message.
This is my model
[Serializable, JsonObject]
public class CompleteOrderRequest : BaseMessageRequest<CompleteOrderRequestDto>
{
}
[Serializable]
[JsonObject, Bind("RequestFrom,RequestBy")]
public abstract class BaseMessageRequest<T> : IBaseMessageRequest<T> where T : class, new()
{
protected BaseMessageRequest()
{
Request = new T();
}
[Required, StringLength(255, MinimumLength = 3)]
[BindProperty(SupportsGet = true), BindRequired]
[FromQuery]
public string RequestBy { get; set; }
[BindProperty(SupportsGet = true)]//, BindRequired]
[FromQuery]
public T Request { get; set; }
}
public class CompleteOrderRequestDto
{
public string OrderNo { get; set; }
}
This is my controller
public async Task<IActionResult> PayNow([FromBody] CompleteOrderRequest request)
{
return View();
}
And this is my javascript code.
var CompleteOrderRequest = {};
CompleteOrderRequest.RequestBy = 'test';
$.ajax({
type: 'POST',
url: '/Orders/PayNow/${CompleteOrderRequest}',
success: function (data) {
if (data.success) {
}
}
});
The error is in this line. I'm encountering error before calling the controller.
CompleteOrderRequest.RequestBy = 'test';
So what's wrong with what Am i doing? And I'm receiving this error
Uncaught SyntaxError: Invalid or unexpected token
When creating your object in JavaScript, you can declare the properties inline like this:
var CompleteOrderRequest = {
RequestBy: "test"
};
You'd also need to ensure you provide that object as the data parameter when posting with ajax.
fix the ajax
$.ajax({
type: 'POST',
url: '/Orders/PayNow',
data: { request: CompleteOrderRequest}
success: function (result) {
if (result.success) {
}
}
});
and when you use only one kind of data from ajax , you don't usually need [FromBody]. Try to change the action too
public async Task<IActionResult> PayNow(CompleteOrderRequest request)
Since you use [FromBody] in action,you need to change your contentType to application/json and convert CompleteOrderRequest to json type:
var CompleteOrderRequest = {};
CompleteOrderRequest.RequestBy = 'test';
$.ajax({
type: 'POST',
url: '/Orders/PayNow',
data: JSON.stringify(CompleteOrderRequest),
contentType:"application/json",
success: function (data) {
if (data.success) {
}
}
});
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.
I want to get data about my user from ajax request. But it never logs anything, which means it never reaches to success part of ajax request.
This is my controller
#Controller
#RequestMapping(value = "/api/profile")
public class ProfilController {
#Autowired
public UserService userService;
#RequestMapping(value = "/show/{username}", method = RequestMethod.GET)
public ResponseEntity<UserDTO> showData(#PathVariable String username) {
User u = userService.findByUsername(username);
if(!userService.findAll().contains(u))
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(new UserDTO(u), HttpStatus.OK);
}
}
And this is my java script file.
$(document).ready(function() {
console.log(localStorage.getItem('loggedIn'));
var usrnm = localStorage.getItem('loggedIn');
$.ajax({
url: "http://localhost:8080/api/user/login/check/"+usrnm,
type: "GET",
headers: {"Authorization": localStorage.jwt},
success: function(data) {
console.log('success');
}
})
$.ajax({
url: "http://localhost:8080/api/profile/show/"+usrnm,
type: "GET",
success: function(data) {
console.log('This part is not executed');
}
})
});
I am new to Spring, actually I am new to programming so sorry if this question is not well formatted
You may have an error in the showData function. You should do the following:
#PathVariable("username") String username
Try to remove this.
#Controller
#RequestMapping("/api/profile") // fixed this!!! remove `value = `
public class ProfilController {
#Autowired
public UserService userService;
#RequestMapping(value = "/show/{username}", method = RequestMethod.GET)
public ResponseEntity<UserDTO> showData(#PathVariable String username) {
User u = userService.findByUsername(username);
if(!userService.findAll().contains(u))
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
return new ResponseEntity<>(new UserDTO(u), HttpStatus.OK);
}
}
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.
Longer title would be:
"Attempts to use an ajax call to the controller to insert search results into a table result in errors while remaining on the same page results in "405" or "Direct self-reference leading to cycle... " errors"
I am trying to find a way to fill a table with search result while staying on same page using an ajax call to the controller.
ajaxCall->Controller->Service(completes search)->Controller(result from search)->back to ajax with response
I have an ajax call that is triggered on form submit after prevent default:
function ajaxGetSearchResults(link, form) {
var myList=[];
var jqxhr = $.ajax({
"url" : link,
"data" : form.serialize(),
"dataType" : 'json',
"type" : "POST",
"headers": {
'Content-Type': 'application/json'
},
"success" : function (response){
console.log("Ajax success");
fillTable(response);
console.log("Search results added to table: "+response);
},
"complete": function(response){
console.log("Ajax call to controller completed");
},
"error": function(){
console.log("Ajax call to controller triggered error");
}
});
}
In the controller I recieve the ajax request as such:
#RequestMapping(value = "/ajaxScriptSearch", method = RequestMethod.POST)
public #ResponseBody List<ResultViewDto> processAJAXRequestSearch(#RequestParam String a1,
#RequestParam String a2, #RequestParam String a3, #RequestParam String a4) {
SearchDto searchDto = new SearchDto();
searchDto.setAttribute1(a1);
searchDto.setAttribute2(a2);
searchDto.setAttribute3(a3);
searchDto.setAttribute4(a4);
try {
/*
calling Service, performing search using searchDto as a parameter, mapping result to resultViewDtos
*/
} catch(Exception e){
/* do something */
}
return resultViewDtos;
}
The call to the service is successfull.
An example of resultViewDtos would be: [viewDto1, viewDto2, viewDto3] where every view dto contains a number of string values which need to be inserted into a table.
I seem to be getting a "HTTP Status 405 - Request method 'GET' not supported" error, but my ajax call is "type: POST".
When I tried doing it with GET insted, I get an "Direct self-reference leading to cycle (through reference chain...)" error.
I am using jackson-core 2.6.2, jackson-databind 2.6.2, Spring 4, Hibernate 4.
I would appericiate any help I can get...
In the end I managed to create a workaround for this.
I have changed my ajax call as such:
function ajaxGetSearchResults(link, form) {
var jqxhr = $.ajax({
"url" : link,
"data" : form,
"dataType" : 'json',
"headers": {
'Accept' : 'application/json',
'Content-Type': 'application/json'
},
"type" : "GET",
"success" : function (response) {
console.log("Ajax success");
fillTable(response);
},
"complete": function(response) {
console.log("Ajax call to controller completed");
},
"error": function() {
console.log("Ajax call to controller triggered error");
}
});
}
And my controller as follows:
#RequestMapping(value = "/ajaxScriptSearch", method = RequestMethod.GET)
public #ResponseBody List<String> processAJAXRequestSearch(#RequestParam String a1,
#RequestParam String a2, #RequestParam String a3, #RequestParam String a4) {
SearchDto searchDto = new SearchDto();
searchDto.setAttribute1(a1);
searchDto.setAttribute2(a2);
searchDto.setAttribute3(a3);
searchDto.setAttribute4(a4);
List<String> result = new ArrayList<String>();
List<ResultViewDto> resultViewDtos = new ArrayList<ResultViewDto>();
try {
/*
calling Service, performing search using searchDto as a parameter, mapping result to resultViewDtos
*/
for(int i=0; i<resultViewDtos.size(); i++){
result.add(resultViewDtos.get(i).toResponseString()); //a new method
}
} catch(Exception e){
/* do something */
}
return result;
}
toResponseString() is a new method I have created in my resultViewDto that returns a string in which the attributes I need are separated by ":".
After filling the result and sending it back to ajax as a response, I then split the recieved response first on (',') to get the individual "rows" equivalent to a single resultViewDto, and then by (':') to get the values for each cell.
There might be a better way of solving it, but this woked like a charm.
I hope this will be usefull for someone else too.