I send the data from the form using XMLHttpRequest to a servlet (Java), but I also need to receive a result message on the same page without overloading it. Can someone with an experienced look tell the beginner what I'm doing wrong would be very grateful

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.onreadystatechange = function () { //этот код не работает, выскакивает alert(200) if(xmlhttp.readyState == 4 && xmlhttp.status == 200){ var response = xhr.responseText; } else { alert(xmlHttp.status); } }; 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!"); } request.getRequestDispatcher("/add.jsp").forward(request, response); } } 

    1 answer 1

     xhr.onload = function () { var response = xhr.responseText; document.getElementById('result').innerHTML = response; };