0

When I try to send data to my controller with an Ajax Post request my @ModelAttribute object doesn't get populated. But when I send the values with form submit it works fine. Please check the code below,

Form,

<form action="#" id="productForm" th:action="@{/save}" th:object="${product}" method="POST">
    <table>
        <tbody>
            <tr>
                <td>Name:</td>
                <td><input id="name" type="text" th:field="*{name}" /></td>
            </tr>
            <tr>
                <td>Brand:</td>
                <td><input id="brand" type="text" th:field="*{brand}" /></td>
            </tr>
            <tr>
                <td>Made In:</td>
                <td><input id="madeIn" type="text" th:field="*{madeIn}" /></td>
            </tr>
            <tr>
                <td>Price:</td>
                <td><input id="price" type="text" th:field="*{price}" /></td>
            </tr>
        </tbody>
    </table>
    <br />
    <button type="submit">Save</button>
    <button type="button" onclick="saveWithAjaxPost();">Save with Ajax Post</button>
</form>

Controller,

@RequestMapping(value = "/saveWithAjaxPost", method = RequestMethod.POST)
@ResponseBody
public ModelMap saveWithAjaxPost(@ModelAttribute Product product) {
    ModelMap model = new ModelMap();
    service.saveProduct(product);
    model.put("MESSAGE", "Success");
    return model;
}

JavaScript,

function saveWithAjaxPost(){

    var params = $("#productForm").serialize();

    $.ajax({

        url:"/saveWithAjaxPost",
        type:"POST",
        contentType:"application/json",
        data:params,
        async:true,
        dataType:"json",
        success:function(response){
            $('#productsListDiv').empty();
            getAllProcucts();
        },
        error:function(response){
            alert(response.message);
        }
    });
}

I get "name=test_name&brand=test_brand&madeIn=test_made_in&price=1000" after serializing the form.

This is what my controller gets when running the code, enter image description here

This must be a pretty simple mistake but I can't figure out what I'm doing wrong here... What could be the issue?

0 Answers0