Czachodym
Czachodym

Reputation: 245

How to show AJAX response data on a website

I'm writting a Spring Boot applicaiton in which I have a website with a submenu with several computer games. When I click on an position in this submenu, I want server to send an image (by image I mean a path to the image) of this game as a response, and after the response comes back to my JS on a website, I want to show it on the website. What I have already done is sending a request to server, and selecting an image based on request data. I don't know how to send a response and use it on my website.
Here is my code:

Java:

@RequestMapping("/change-game")
public String changeGame(HttpServletRequest request, @RequestBody GameData data){
    File file;
    String game = data.getName();
    switch (game) {
        //some code which actually works. I removed it to save space
    }
    request.setAttribute("gameIcon", file);
    return "index";
}

JavaScript:

$("#selectGameSubmenu li").click(function(e){
    e.preventDefault();
    var option = $(this).data("option");
    console.log(option + " " + JSON.stringify({"option": option}));
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/change-game",
        data: JSON.stringify({name: option}),
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    });
});

HTML:

 <img src="${gameIcon}" alt="${altGameIcon}"
             style="width:100px;height:100px" class="gameLogoCenter"/>

Upvotes: 2

Views: 106

Answers (1)

Phil
Phil

Reputation: 164936

I would add a new method that returns only the image path for your AJAX calls to consume.

For example

@ResponseBody
@PostMapping("/change-game-icon")
public String changeGameIcon(@RequestBody GameData data) {
    File file;
    String game = data.getName();
    switch (game) {
        //some code which actually works. I removed it to save space
    }
    return file.toString();
}

and in your JS

$.ajax({
  url: '/change-game-icon',
  method: 'post', // or "type" if your jQuery is really old
  data: JSON.stringify({name: option}),
  dataType: 'text',
  contentType: 'application/json'
}).done(iconPath => {
  $('img.gameLogoCenter').prop('src', iconPath)
})

Upvotes: 1

Related Questions