2

I'm trying to call my Spring controller using Ajax and submitting a form.

Function always retrieves the error window. I tried changing the URL parameter to "/profile", "profile" or "PrivateAreaController/profile", but I keep getting the same error.

My main.js file and controller are placed in the following order:

-->Mainfolder
    -->src
       -->java
          -->controller
              -->PrivateAreaController.java
       -->resources
           -->static
              -->js
                 -->main.js

My controller is called PrivateAreaController

Ajax Code

$('#sampleForm').submit(
    function(event) {
        var firstname = $('#firstname').val();
        var lastname = $('#lastname').val();
        var data = 'firstname='
            + encodeURIComponent(firstname)
            + '&lastname='
            + encodeURIComponent(lastname);
        $.ajax({
            type : "POST",
            dataType: "json",
            url : '@Url.Action("callingcontroller","PrivateAreaController")',
            contentType: "application/json; charset=utf-8",
            data : data,
            success : function(response) {
                alert( response );
            },
            error : function() {
                alert("not working");
            }
        });
        return false;
    }); 

Spring code

@RequestMapping(value = "/profile", method = RequestMethod.POST)
        public @ResponseBody
        String processAJAXRequest(
                @RequestParam("firstname") String firstname,
                @RequestParam("lastname") String lastname   ) {
            String response = "";

            System.out.println("working");
            return response;
        }

HTML form

<form id="sampleForm" method="post" action="/profile">
         <input type="text" name="firstname" id="firstname"/>
         <input type="text" name="lastname" id="lastname"/>
         <button type="submit" name="submit">Submit</button>
</form>

EDIT:

I found the answer.. i needed to add

@CrossOrigin(origins = "http://localhost:8080")

before the @RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)

pepote
  • 313
  • 7
  • 21

4 Answers4

1

I found the answer.. i needed to add

@CrossOrigin(origins = "http://localhost:8080")

before the @RequesMapping parameter and change the url parameter of the ajax call to url: 'http://localhost:8080/(your requestmapping parameter)

pepote
  • 313
  • 7
  • 21
1

This worked for me using springboot with thymeleaf, made small modification to one of the answers on this post How do you get the contextPath from JavaScript, the right way?

In the HTML

        <html>
            <head>
                <link id="contextPathHolder" th:data-contextPath="@{/}"/>
            <body>
                <script src="main.js" type="text/javascript"></script>
            </body>
        </html>

THEN IN JS

  var CONTEXT_PATH = $('#contextPathHolder').attr('data-contextPath');
  $.get(CONTEXT_PATH + 'action_url', function() {});
Winter MC
  • 355
  • 2
  • 7
0

What is error you are getting, Press F12 and go to Network tab and the press submit button now see the url, try adding url:"../your service URL..

Leo
  • 1
0

Well. I never seen this part before.

@Url.Action("callingcontroller","PrivateAreaController")

I normally do like as below:

 $.ajax({
        type : "POST",
        dataType: "json",
        url : '/profile',
        contentType: "application/json; charset=utf-8",
        data : data,
        success : function(response) {
            alert( response );
        },
        error : function() {
            alert("not working");
        }
 });

But it can have a problem with the contextPath. So, What I do is adding 'request.getContextPath()/' as below:

     $.ajax({
        type : "POST",
        dataType: "json",
        url : '${request.getContextPath()}/profile',
        contentType: "application/json; charset=utf-8",
        data : data,
        success : function(response) {
            alert( response );
        },
        error : function() {
            alert("not working");
        }
    });

The contextPath has the URL of your start page. For instance, 'www.google.com' or 'www.naver.com'

But in general, Since I personally use the contextPath a lot, I make a value and keep it.

var context = ${request.getContextPath()};

Then, your code will look neat and easy to reuse.

And also you can figure it out with the error attribute.

        error : function(err) {
            console.log("not working. ERROR: "+JSON.stringify(err));
        }

I hope this works out.

c-an
  • 3,543
  • 5
  • 35
  • 82