2

My intent is to pass a couple of parameters to an action in struts2, but I want that these parameters have to be hidden, so the GET call is not recommended. I thought that a post or ajax call in jQuery could be a good idea to do so, but the parameters are null and the redirect to the jsp page doesn't work. Here are the Action and the javascript codes:

MyAction.java

public class MyAction extends ActionSupport{

     private Long pkId;
     private String type;

     public String execute() {
        String pkId = getPkId();
        String type = getType();
        return Action.SUCCESS;
     }
}

file.js

function myFunction(){
    var pkId = "pkId1";
    var url = "./myAction.action";
    var type = "type1";
    $.ajax(url, {pkId : pkId, type : type});
}

Updated code:

function myFunction(){
        var pkId = "pkId1";
        var url = "./myAction.action";
        var type = "type1";
        $.post(url, {pkId : pkId, type : type}, function(resp){
             // resp is the response from the server after the post request.
        });
    }

chrisblo
  • 768
  • 1
  • 13
  • 30
  • You didn't specify that you wanted a `POST` request. The default for a `$.ajax()` call is `GET`. Specify the `method` as explained in the doco. – nnnnnn Jun 23 '15 at 14:13
  • possible duplicate of [hide passed parameter from jsp to struts2 action class](http://stackoverflow.com/questions/16376190/hide-passed-parameter-from-jsp-to-struts2-action-class) – Roman C Jun 24 '15 at 07:44

2 Answers2

0

What you have done is right. Instead of the $.ajax(), use the $.post shortform:

$.post(url, {pkId : pkId, type : type}, function (resp) {
  // resp is the response from the server after the post request.
});

So the file.js contains:

function myFunction() {
    var pkId = "pkId1";
    var url = "./myAction.action";
    var type = "type1";
    $.post(url, {pkId : pkId, type : type}, function (resp) {
      // resp is the response from the server after the post request.
    });
}

If you don't want an Asynchronous request, make it a default form.

function myFunction() {
    var pkId = "pkId1";
    var url = "./myAction.action";
    var type = "type1";
    var FormD = '<form method="post" action="' + url + '" id="frmFakeSubmit">';
    FormD += '<input type="hidden" name="pkId" value="' + pkId + '" />';
    FormD += '<input type="hidden" name="type" value="' + type + '" />';
    FormD += '</form>';
    $("body").append(FormD);
    $("#frmFakeSubmit").submit();
}

Hope this helps!

Praveen Kumar Purushothaman
  • 164,888
  • 24
  • 203
  • 252
0
 $.ajax({
     url: "<your url>",
     type: "POST",
     data: JSON.stringify(<your data>)
 }).done(function(response) {
    //TODO response from the sever
 });

Since the default request method of $.ajax is GET, you should specify the type parameter as 'POST' to do a post request.

Tino M Thomas
  • 1,676
  • 2
  • 16
  • 24