Search code examples
javajqueryajaxstruts

JQuery.ajax error 400 bad request with Struts


I have a website, made with Struts1, java and JSPs, and I need to get datas from a webservice dynamically. I call my java method using AJAX in my JSP, but I get an Error 400: bad request no matter what I try. So here is my Javascript function in my JSP:

var panierSansFares=new Array();

function myFunction(){

        $.ajax({
            url: "myPath/getFares.do?method=doGet",
            type: 'GET',
            dataType: 'json',
            contentType: "application/json; charset=utf-8", // this
            data: 'panierSansFares='+JSON.stringify(panierSansFares),
            success: function(res) {
                alert(res);
            }
        });
  }

Note that panierSansFares in an array of objects, and it is not empty when the function is called. And in my STRUTS, the action:

<action path="/getFares" 
            type="myPath.GetFaresServlet"
            scope="request" >
        </action>

And lastly, my java code:

public class GetFaresServlet  extends Action {
   private static final long serialVersionUID = 1L;

   protected void doGet(HttpServletRequest request, HttpServletResponse response, ActionMapping actionMapping) throws IOException {
                  /**Some stuff**/

   }
}

My Error 400 comes from the Struts, because I can see a "Invalid path was requested" error in Chrome developer tools (network tab).

I tried to bypass Struts and just call my java directly as a servlet, but I couldn't do it, I got error404.

I've never used ajax with Struts before so I'm lacking knowledge to find where the problem is.

Thank you


Solution

  • I did not understand your problem but i follow this code for api call

    function APICall(url, methodType, data) {
        var d = $.Deferred();
        methodType = methodType || "GET";
        data = data || null;
        $.ajax({
            url: url,
            async: true,
            method: methodType,
            data: data,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response, status, request) {
                d.resolve(response, status, request);
            },
            error: function (error) {
                d.resolve(error.responseJSON);
            }
        });
        return d.promise();
    }
    APICall(url, methodType, data).done(function (response, status, request) {
        d.resolve(response, status, request);
    }).fail(function (response) {
        d.resolve(response, status, request);
    });