Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit spring form in ajax(jquery) with modelAttribute

I am new to Spring MVC. I have a form like this,

<form:form action="/myaction.htm" method="post" modelAttribute="myForm" id="formid"> and a controller that returns json

public @ResponseBody ResultObject doPost(@ModelAttribute("myForm") MyForm myForm){ System.out.println("myform.input"); }

I am able to submit this using$("#formid").submit(); and my modelAttribute is working fine, taking values from UI.

my question is, how to submit this form in jquery ajax way? I tried this,

$.ajax({
type:"post",
url:"/myaction.htm",
async: false,
dataType: "json",
success: function(){
alert("success");
}

});

the form is submitted but modelAttribute values are nulls, how to include modelAttribute object(object that form is using) while submitting?

like image 621
Rony Avatar asked Dec 19 '12 17:12

Rony


1 Answers

You need to post the data. The way I typically do it is using the following.

var str = $("#myForm").serialize();

$.ajax({
    type:"post",
    data:str,
    url:"/myaction.htm",
    async: false,
    dataType: "json",
    success: function(){
       alert("success");
    }
});
like image 57
Manuel Quinones Avatar answered Sep 18 '22 14:09

Manuel Quinones