Return data from Java to Ajax using Json

Asked

Viewed 1,150 times

1

I have a Java application, and a module that inserts products into the base using REST. At the base the product id is autoincremental, and as soon as I add the same at the base, I need the id for the table with the products to be updated with the id correctly. Follow the codes:

AJAX:

$.ajax({
        type: 'POST',
        url: '/minhaaplicacao/rest/produto',
        data: dataJson,
        contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                **//aqui preciso pegar o ID, pelo objeto 
                    //que foi adicionado na base de dados
                    //e retornar para o novoId.
                    //o commit true atualiza a tabela no html, 
                    //inserido o novo registro, o novoId 
                    //é o valor que preciso pegar, 
                    //o qual foi inserido na base** 
                commit(true, novoId);
        }, 
        error: function () {
            commit(false);
            alert('deu erro');
        }
    });

On the server side I have java returning a Response with the product object, with all the information inserted in the database:

JAVA:

@POST
@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
public Response adicionar(Produto produto)
{
    Produto produtoInserido = ProdutoService.insert(produto);
    return Response.ok().entity(produtoInserido).build();
}

It turns out, the product id is auto incremental, and I have the value only after insertion, and I need it returning to ajax, so that the product listing table is updated with correct id.

1 answer

4


Just in return, put a parameter, as shown in the ex below:

$.ajax({
        type: 'POST',
        url: '/minhaaplicacao/rest/produto',
        data: dataJson,
        contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (r) {
                    TEUID = r.Id
        }, 
        error: function () {
            commit(false);
            alert('deu erro');
        }
    });
  • Thanks Rod, it was very helpful. And solved my problem, thank you.

  • Could you show where you placed a parameter? I could not identify.

  • Success: Function(PARAMETRO) { }

Browser other questions tagged

You are not signed in. Login or sign up in order to post.