CR7
CR7

Reputation: 79

Jquery Ajax send contentType application/json and java get null

When I send a Json object from ajax jquery with the "contentType" property, the back-end that this case is java , not find the json element or the request is null

this is JS

    var urlInsert = '/SAF/ajax/supplier/insert';
        console.log(rfc);
        $.ajax({
            type : 'POST',
            url : urlInsert,
            data:{
                proveedor : jsonObj //jsonObj is a JSON.stringify()
            },
            dataType : "json",
            contentType : "appliaction/json",
            mimeType : "applicaction/json",
            success : onInsert,
            error : function(data, status, er) {
                alert("Load Data: " + data + ", Estatus: " + status + ", Error: "
                        + er);
            }
        }); 

it's method in my controller JAVA

    @RequestMapping(value="insert",method=RequestMethod.POST)
public void onInsert(HttpServletRequest request, HttpServletResponse response){
    Gson gson = new Gson();
    SafTcProveedor proveedor = gson.fromJson(request.getParameter("proveedor"), SafTcProveedor.class);
    System.out.println(proveedor);

}

Upvotes: 1

Views: 1873

Answers (2)

321hendrik
321hendrik

Reputation: 177

You have a typo in there and your data object should be a JSON object if you set its dataType to json, hence the quotes around proveedor.

This code should be working:

var urlInsert = '/SAF/ajax/supplier/insert';
        console.log(rfc);
        $.ajax({
            type : 'POST',
            url : urlInsert,
            data:{
                "proveedor" : jsonObj //jsonObj is a JSON.stringify()
            },
            dataType : "json",
            contentType : "application/json",
            mimeType : "application/json",
            success : onInsert,
            error : function(data, status, er) {
                alert("Load Data: " + data + ", Estatus: " + status + ", Error: "
                        + er);
            }
        });

Or you could use jQuery's post function:

$.post('/SAF/ajax/supplier/insert', {proveedor: jsonObj})
    .done(onInsert)
    .fail(function (jqXHR, textStatus, errorThrown) {
        alert('error', errorThrown);
    });

Upvotes: 2

Kim Prado
Kim Prado

Reputation: 1

You should put a plain object or string in data attribute. See http://api.jquery.com/jquery.getjson/.

var urlInsert = '/SAF/ajax/supplier/insert';
        console.log(rfc);
        $.ajax({
            type : 'POST',
            url : urlInsert,
            data: jsonObj, //jsonObj is a JSON.stringify()
            dataType : "json",
            contentType : "appliaction/json",
            mimeType : "applicaction/json",
            success : onInsert,
            error : function(data, status, er) {
                alert("Load Data: " + data + ", Estatus: " + status + ", Error: "
                        + er);
            }
        }); 

Upvotes: 0

Related Questions