DaniR
DaniR

Reputation: 85

404 Not Found in AJAX post call

I'm using Spring MVC and when I do an ajax post call I get a 404. My controller looks like this:

@Controller
@RequestMapping("/mensaje")
public class MensajeController {

    public MensajeController() {
        super();
    }

    @ResponseBody
    @RequestMapping(value = "/prueba", method = RequestMethod.POST)
    public String prueba(@RequestParam("cuerpo") final String cuerpo) {
        String b = null;

        String a = null;

        return b;
    }
}

And the ajax call like this:

<script type='text/javascript'>
    $(document).ready(function() {      
        $("#save").click(function(e) {
            e.preventDefault();
            var myEditor = document.querySelector('#editor');
            var html = myEditor.children[0].innerHTML;

            $.ajax({
                    type : "POST",
                    url : "/Gestion-Practicas/mensaje/prueba",
                    dataType: "json",
                    contentType: 'application/json; charset=utf-8',
                    data: {'cuerpo': html},
                    async: false,
                    cache: false,
                    delay: 15,
                    success: function(data){
                        alert('success');
                    },
                    error: function (xhr) {
                        alert(xhr.responseText);
                    }
                });     
        });

    });
</script>

The url from where I do the ajax call is:

http://localhost:8080/Gestion-Practicas/mensaje/create.do

The url who appears in the Chrome's console after doing the ajax call is:

http://localhost:8080/Gestion-Practicas/mensaje/prueba

Summarizing, the ajax call never reaches the controller's method and I don't know why

Upvotes: 2

Views: 539

Answers (1)

front_end_dev
front_end_dev

Reputation: 2056

Instead of @RequestParam use @RequestBody

@RequestParam - It's used for query parameters in request url.

@RequestBody - It's a post body payload.

Convert your String cuerpo to a class with property String cuerpo

public class PostBody{
  private String cuerpo;
  public String getCuerpo(){
    return this.cuerpo;
   }

   public void setCuerpo(String cuerpo){
     this.cuerpo = cuerpo;
   }
}

Now your line public String prueba(@RequestParam("cuerpo") final String cuerpo)

Updated will look like public String prueba(@RequestBody final PostBody postBody).

Upvotes: 3

Related Questions