In case of successful execution of the XMLHttpRequest request to the servlet, you need to display the message "Student added to the database" on the page. Problem: the page is reloading, the message remains on the page before the reload and is not visible. It is necessary that the message be highlighted, while not the whole page is updated, but only the form (ideally) or the form is hidden, because. if you leave it in the previous state, when you press submit again, the same data will be entered again. something like that ... Help please who than can
add.jsp:
<h1 id='result'></h1> //выводится сообщение о результате <h2>Add student</h2> <form> <input type = "text" id="firstname" name="firstname"><br> <input type = "text" id="secondname" name="secondname"><br> <input type="submit" id="button" value="Add student" onclick="add()"> </form> js:
function add() { var xhr = new XMLHttpRequest(); var fname = document.getElementById("firstname").value; var surname = document.getElementById("secondname").value; var button = document.getElementById("button").value; dat = "firstname="+encodeURIComponent(firstname)+"&secondname="+encodeURIComponent(secondname)+"&button="+encodeURIComponent(button); xhr.open('POST', 'servlet', true); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); xhr.send(dat); xhr.onload = function () { var response = xhr.responseText; document.getElementById("result").innerHTML = response; }; } servlet:
public void doPost(HttpServletRequest request, HttpServletResponse response){ if(request.getParameter("button".equals("Add student")){ if(request.getParameter("firstname").matches("[A-Za-z]{2,}") && request.getParameter("secondname").matches("[A-Za-z]{2,}")) { studentDao.create(new Student(0, request.getParameter("firstname"), request.getParameter("secondname"))); response.getWriter().write("Student successfully added to the Database!"); //нужно вывести это сообщение на страницу } else { response.getWriter().write("Student has not been added to the Database, input correct data!"); //это сообщение в случае неудачи успешно выводится } } }