Home > Enterprise >  When I use Ajax with spring controller it's redirected
When I use Ajax with spring controller it's redirected

Time:10-08

So, I trying to create a Spring MVC app like "Cinema" app. I'm using RestController with Get method that produce JSON like response.

private SessionService sessionService;

public SessionController(SessionService sessionService) {
    this.sessionService = sessionService;
}

@GetMapping(value = "/test")
public String getSearchField() {
    return "sessionsSearching";
}


@GetMapping(value = "/search", consumes = MediaType.ALL_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody
String searching(@ModelAttribute("filmName")String request) {
    List<Session> serviceResponse = sessionService.searchByRequest(request);
    JSONArray sessionsJson = new JSONArray();
    for (Session s : serviceResponse) {
        JSONObject filmJson = new JSONObject();
        filmJson.put("name", s.getFilm().getTitle());
        JSONObject sessionJson = new JSONObject();
        sessionJson.put("id", s.getId());
        sessionJson.put("dateTime", s.getDate());
        sessionJson.put("film", filmJson);
        sessionsJson.add(sessionJson);
    }
    return sessionsJson.toJSONString();
}

And I want search sessions and films without redirect. I'm trying create Ajax with jQuery

<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" >
    $(document).ready(function () {
        $("#submitRequest").submit(function (e) {

            e.preventDefault();

            let url = $(this).attr('action');

            $.ajax({
                type: "GET",
                url: url,
                dataType: "json",
                data: {filmName: $("#filmName").val()},
                success: function (data) {
                    display(data);
                }
            });
        })
    })
</script>
<form action="/sessions/search">
    <input name="filmName" type="text" placeholder="Search...">
    <input type="submit" id="submitRequest">
</form>
<div>
    <p id="result"></p>
</div>
</body>

And when I load my html-page and put "Avatar" (for example) in search field - I'm redirected on http://localhost:8080/sessions/search?filmName=Avatar with json-string on page

pls, help.

CodePudding user response:

Firstly, you can not use the same <script> tags to import jQuery and place your custom Javascript.

You have to use two separate <script> tags.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" ></script>

<script type="text/javascript"> // Here comes your custom JS code </script>

Secondly, you are not submitting the button. You have to write your script for the form submit action.

$("#myForm").submit(function (e) {
        
    e.preventDefault();
    let url = $("#myForm").attr('action');

    $.ajax({
        method: "get",
        url: url,
        dataType: "json",
        data: {filmName: $("#filmName").val()},
        success: function (data) {
            display(data);
        }
    });
});

Suggestion:
Since you are firing an AJAX call and not reloading the page, you can add a simple button to the form and write your code to the button click function without risking a reload in some browsers.

<button id="submitRequest">SUBMIT</button>

$("#submitRequest").click(function (e) { // Button click functions });
  • Related