Help Rest + Json + Jquery

124 views
Skip to first unread message

Jeffersson Araujo

unread,
Oct 29, 2011, 7:28:58 PM10/29/11
to restfu...@googlegroups.com
Hello Everyone, I am already a few days trying to solve a problem like post a request via Json RESTEasy using the library, I would send the data from an HTML form using jQuery, but I am not having success, someone could help me or give me a hint better than I am using?

The context is a user, the process is complete the form and save these data in the database via JPA, my model is mapped so as follows:


@XmlRootElement(name = "user")
public class User {

    private String nome;
    private String sobrenome;

    public User(String nome, String sobrenome) {
        this.nome = nome;
        this.sobrenome = sobrenome;
    }

    public User() {
    }

    @XmlElement
    public String getNome() {
        return nome;
    } ...
--------------------------------------------
And my class service that uses the rest is with the following method:

    @POST
    @Path("createuser")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createNewUser(JAXBElement<User> user) {
        UserDaoImpl daoImpl = new UserDaoImpl();
        daoImpl.createUser(user.getValue());
        URI userUri = uriInfo.getAbsolutePathBuilder().
                path(user.getValue().getNome().toString()).
                build();
        return Response.created(userUri).build();
    }
----------------------------------------------------------------------------
In the HTML my call I'm using this jQuery function:
$(document).ready(function() {
    $("#formCadastro").submit(function(event){
        event.preventDefault();
        $.post("/auth/createuser",  $("#formCadastro").serialize(),
            function() {
                alert("User Created !");
            });
    });
});

Someone could help me or make a comment about what I should use?

Thank You !
--
╔═══════════════════════════════╗
    Jefferson de Araújo Alves  
    Graduando em Sistemas de Informação
    Universidade Federal da Paraiba - Campus IV
    Página Pessoal: www.jeffersonaraujo.com
╚═══════════════════════════════╝

Daniel Yokomizo

unread,
Oct 30, 2011, 4:44:30 PM10/30/11
to restfu...@googlegroups.com

By default JQuery sends post as application/x-www-form-urlencoded. You
need to explicitly set the content type. I do it like this:


$.ajax({type: 'POST',
url: $(this).attr("action"),
data: $.toJSON(data),
contentType: "application/json"

Reply all
Reply to author
Forward
0 new messages