Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pass javascript response variable to spring controller function

The following javascript code works with the facebook login window appearing and allowing a user to login. The response values are captured and I know it works as alerts appear where setup but I cannot pass the value back to a controller method.

 @RequestMapping(value ="/getAccessToken" , method = RequestMethod.POST)
 public @ResponseBody String getAccessToken(@RequestBody String token){

     System.out.println(token);

     return token;
  } 

Javascript method called:

    function doLogin() {
        FB.login(function(response) {
        alert(response);
        console.log(response);
        if (response.authResponse) {
                    alert(response.authResponse.userID);
                    alert(response.authResponse.accessToken);
                    var Token = response.authResponse.accessToken;
                    alert(Token);
                    $.ajax({
                        type: "POST",
                        url: "/HelloController/getAccessToken",
                        data: Token,
                        success: function (result) {
                              alert("Token");
                        },
                        error: function (result) {
                              alert("oops");
                        }
                    });
                     document.getElementById('loginBtn').style.
         display = 'none';
         getUserData();
        }}, {perms:'manage_pages', 
       scope: 'email,public_profile', return_scopes: true});
     };

The error I get is the following:

WARN 25660 --- [nio-8080-exec-9] 
o.s.web.servlet.PageNotFound             : 
Request method 'POST' not supported

Appreciate responses.

like image 908
vbNewbie Avatar asked Oct 30 '22 14:10

vbNewbie


1 Answers

The problem could be that you are using a new version of JQuery that sends request data as post form data instead of JSON as default. Try changing your ajax call to the following. The form data would not be recognized by your controller so if this is the case you should see a 404.

$.ajax({
        type: "POST",
        traditional: true,
        url: "/HelloController/getAccessToken",
        data: JSON.stringify(Token),
        success: function (result) {
           alert("Token");
        },
        error: function (result) {
          alert("oops");
        }
      });

For reference see this post: Send JSON data via POST (ajax) and receive json response from Controller (MVC)

like image 147
Pablo Jomer Avatar answered Nov 12 '22 16:11

Pablo Jomer