Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you are beginner in IT field, you are more then welcome to ask questions, it will help you to learn faster. We are here to help you.

We are always beginner in something, we just need to remember it along the way.

there are no wrong questions - Ask Question

JavaScript Ajax POST request with Java Spring MVC controller

0 contributions
1 points

In JavaScript it is possible to make AJAX POST request in following way.

Note: scroll to See also section to see other variants of AJAX requests.

1. Pure JavaScript (Vanilla JS) AJAX POST request

In this section XMLHttpRequest object usage to make POST request is presented.

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<body>
<script>

    var xhr = new XMLHttpRequest();

    xhr.onreadystatechange = function () {
        if (xhr.readyState == XMLHttpRequest.DONE) {
            if (xhr.status == 200) {
                document.body.innerText = 'Response: ' + xhr.responseText;
            } else {
                document.body.innerText = 'Error: ' + xhr.status;
            }
        }
    };

    var data = 'This is my data';
    
    xhr.open('POST', '/examples/echo', true);
    xhr.send(data);

</script>
</body>
</html>

2. Spring MVC server site POST methods example

In this section simple Spring backend that handle POST method requests is presented.

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class EchoPostController {

    @RequestMapping(value = "/examples/echo", method = RequestMethod.POST)
    @ResponseBody
    public String makePostEcho(@RequestBody String data) {
        return data;
    }
}

See also

  1. JavaScript Ajax GET request with Java Spring MVC controller
  2. JavaScript - how to make ajax request?

References

  1. Ajax (programming) - Wikipedia
  2. XMLHttpRequest.prototype.send method - MDN Docs
0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more