Will Will - 1 month ago 13
Javascript Question

Struts 2 action method not invoked upon form submission

function test() {
var obj = document.createElement("FORM");
obj.action="SomeAction!thisMethod.action";
obj.submit();
}


However, the action method is not invoked at all.

Action mappings look good in
struts.xml
but just in case you're wondering,

<action name="SomeAction" class="com.test.SomeAction">
<result ...>...</result>
</action>


It's working fine if I have a Struts2 form on that page, but when there's no forms and I want to invoke the action method with a dummy form object, it does not work.

I feel like I'm missing something in the form object.

Answer

You need to add a newly baked form to the body of document before invoking submit().

document.body.appendChild(obj);

In Struts2 s:form the attributes are auto generated. You don't need every of those attributes to submit the form with dummy form element.

If you use jQuery you can do

$("<form>", {    
    "action": "SomeAction!thisMethod.action"
}).appendTo(document.body).submit();
Comments