Почему отрисовка элементов опаздывает на 1: SPRING BOOT, AJAX, JQUERY
Только разбираюсь с AJAX, поэтому не судите сторого. Добавил метод POST, который добавляет юзера в список юзеров. Но проблема в том, что при первом нажатии на кнопку, новый юзер не отрисовывается, а отрисовывается только на 2 нажатие и так далее. Как будто showUsers() вызывается еще до добавления в бд.
Controller
package com.example.spring_jquery_ajax.controller.rest;
import com.example.spring_jquery_ajax.model.User;
import com.example.spring_jquery_ajax.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping()
public List<User> getUser(){
return (List<User>) userRepository.findAll();
}
@PostMapping
public void addUser(@RequestBody User user){
userRepository.save(user);
}
}
Html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Users</title>
<script type="text/javascript" th:src="@{/static/js/jquery-3.6.0.min.js}"></script>
<script type="text/javascript" th:src="@{/static/js/script.js}"></script>
</head>
<body>
<div id="test_user">
</div>
<form>
<input id="inp_phone" type="text" placeholder="Введите номер"/>
<input id="inp_name" type="text" placeholder="Введите имя"/>
<input type="button" value="Добавить" onclick="addUser()"/>
</form>
</body>
</html>
Script
function showUsers() {
console.log("showUsers starts")
$.get("/user", function (data) {
let table = "<table border=1>"
for (let i = 0; i < data.length; i++) {
table = table +
"<tr>\n" +
"<td>\n" +
data[i].phone +
"</td>\n" +
"<td>\n" +
data[i].name +
"</td>\n" +
"</tr>\n"
}
table = table + "</table>"
$("#test_user").html(table)
})
}
$('document').ready(showUsers)
function addUser() {
$.ajax({
url: "/user",
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({
phone: $("#inp_phone").val(),
name: $("#inp_name").val()
}),
success: showUsers()
})
}