Srinivas Raju
Srinivas Raju

Reputation: 131

struts2 ajax call response always shows null

I am trying to call the struts2 action class from my jsp using ajax. I can hit the action class and able to pass the parameters to action class. But the response that comes from action class to my ajax request is always null

All setters and getters are set correctly and they are working fine when I see in debug sysouts

Action Class

@Override
@Action(value = "/search",
          results = { @Result(name = "success", type="json")})
public String execute() throws ParseException
{


    this.setName(this.term+": "+this.pos);
    System.out.println("Name: "+Name);

    JSONObject json = (JSONObject)new JSONParser().parse(Name);


    return ActionSupport.SUCCESS;
}

jsp

function Search()
{
    var term = document.getElementById("term").value;
    var pos = document.getElementById("pos").value;
    var itr = document.getElementById("itr").value;
    var pri = document.getElementById("pri").value;
    var atb = document.getElementById("atb").value;
    var jsonData = {};

    jsonData.term = term;
    jsonData.pos = pos;
    jsonData.itr = itr;
    jsonData.pri = pri;
    jsonData.atb = atb;

     $.ajax({
         type: "POST",
         url: "search",
         dataType: "json",
         data: jsonData,
        success: function(response){
            console.log(""+response);
            alert('Name: '+response.Name);
            //alert('Length: '+data[0].length);

          /*  $.each(data[0],function(index, value){
                alert("value " +value);
               });*/
            },
     error:  function(response){
         alert(response);
         alert(response.length);

         $.each(response,function(index, value){
            alert("value " + value);
            });
     }

     });

} 

I can see the response always as null. I am not sure what is going wrong, but seems the coding part is correct. Am I doing some mistake in ajax call?

Upvotes: 0

Views: 592

Answers (1)

Andrea Ligios
Andrea Ligios

Reputation: 50281

  1. As clearly explained in this answer, you need to use the JSON plugin, that will serialize the entire action (or a single root object when needed). You don't need then to do the parsing yourself, just evaluate the name variable.
  2. To send JSON from JSP to action instead you need to use the JSON Interceptor in your stack.
  3. Ensure you have getters and setters for everything.
  4. Your Name variable should be name, both in Java and in Javascript. Only the accessors / mutators should use the capitalized N (getName, setName).
  5. If the error persists, check carefully console and logfiles for errors, with devMode set to true.
  6. Since this comment has gone too far, I've turned it into an answer :)

Upvotes: 1

Related Questions