Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

423
Views
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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!