Arpan Das
Arpan Das

Reputation: 1037

Request method 'POST' not supported for ajax call

I am making an ajax call to my spring controller for create some data in db, the call is like:

function myfunc(pId,cId,paIndex,cIndex,type)
{
    $.ajax({
        type : "POST",
        url : "./home/useraction/save",
        data : {
            pId : pId,
            cId : cId,
            type : type
        },
        contentType : "application/json; charset=utf-8",
        dataType : "json",
        async : true,
        success : function(data) {
            alert(data);
        }
    });
}

and my controller is like:

@Controller
@RequestMapping("/home")
public class HomeController 
{
    @RequestMapping(value="/useraction/save" ,method = RequestMethod.POST)
    public @ResponseBody GenericResponse save(Model model,HttpServletRequest request) throws Exception 
    {
        String actionType = request.getParameter("type");
        try
        {
            if(actionType != null)
            {
                if (UserActionTypeEnum.UPVOTE.name().equalsIgnoreCase(type)) {
                    // do something
                } else if (UserActionTypeEnum.DOWNVOTE.name().equalsIgnoreCase(actionType)) {
                    // do something
                } else if (UserActionTypeEnum.SHARE.name().equalsIgnoreCase(actionType)) {
                    // do something
                } else if (UserActionTypeEnum.ADD_POST_TO_BANK.name().equalsIgnoreCase(actionType)) {
                    // do something
                }
            }
        }
        catch (Exception e) {
            logger.error("Exception in saveUserActionOnPost() >> " + e.getStackTrace());
        }
        return "success";
    }
}

but I am getting the following error:

HTTP Status 405 - Request method 'POST' not supported, The specified HTTP method is not allowed for the requested resource Any help, what is wrong here

Upvotes: 2

Views: 10432

Answers (2)

Arpan Das
Arpan Das

Reputation: 1037

Actually it is a secured url. Using spring security in my product. Need to send csrf information in ajax call. then it worked

var token = $('#csrfToken').val();
var header = $('#csrfHeader').val();

$.ajax({
     type : "POST",
     url : "./home/useraction/save",
     data : {
        pId : pId,
        cId : cId,
        type : type
     },
    async : true,
    beforeSend: function(xhr) {
        xhr.setRequestHeader("Accept", "application/json");
        xhr.setRequestHeader("Content-Type", "application/json");
        xhr.setRequestHeader(header, token);
    },

Upvotes: 4

sanjay
sanjay

Reputation: 437

I suggest write full requested url into controller same as ajax. write this into ajax type : 'POST', dataType: 'json',

Upvotes: 1

Related Questions