I wish I could get your help! I'm wanting to load a grid and a drop-down list on my HTML page, I'm doing it from javascript but having a servlet as a controller since it's a didactic project, the problem arises when I have a switch with the flag variable in the servlet, and when loading my page and call the methods cargaGrillaMenuitem and cargaComboMenu both are sent by the method POST but in the servlet first I receive the answer of one and then to receive from the other my variable is over, I pass my code so that they understand better. This is my JS:
cargarGrillaMenuItem();
cargarComboMenu();
function cargarGrillaMenuItem() {
var xhr = new XMLHttpRequest(), //
method = "POST",
url = "/seguro_medico/MenuitemCTR";
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
//alert(xhr.responseText);
var json = JSON.parse(xhr.responseText); //reponseText returns the entire JSON file and we assign it to a javascript variable "json".
var i;
var valorTabla = "";
for (i = 0; i < json.length; i++) {
//mecanismo para cargar tabla
valorTabla += "<tr onclick=\"recuperarDeGrilla(" + json[i].id + " ,'" + json[i].nombre + "', '" + json[i].url + "', " + json[i].menu.id + " , 'menuitem_id' , 'menuitem_nombre','menuitem_url','comboMenu')\">" +
"<td>" + json[i].id + "</td>" +
"<td>" + json[i].nombre + "</td>" +
"<td>" + json[i].url + "</td>" +
"<td class=\"w3-hide\">" + json[i].menu.id + "</td>" +
"<td>" + json[i].menu.nombre + "</td>" +
"</tr>";
}
document.getElementById("cuerpoTablaMenu").innerHTML = valorTabla;
}
};
xhr.send(JSON.stringify(datos = {bandera: 6}));
}
function cargarComboMenu() {
var xhr = new XMLHttpRequest(), //
method = "POST",
url = "/seguro_medico/MenuitemCTR";
xhr.open(method, url, true);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
//alert(xhr.responseText);
var json = JSON.parse(xhr.responseText); //reponseText returns the entire JSON file and we assign it to a javascript variable "json".
var i;
var valorOption = "";
for (i = 0; i < json.length; i++) {
//mecanismo para cargar lista desplegable
valorOption += "<option value=" + json[i].id + ">" + json[i].nombre + "</option>";
}
document.getElementById("comboMenu").innerHTML = valorOption;
}
};
xhr.send(JSON.stringify(datos = {bandera: 5}));
}
and this is the servlet:
package Controlador;
import Genericos.Metodos_genericos;
import Seguro.Dao.MenuDAO;
import Seguro.Dao.MenuitemDAO;
import Seguro.Dto.MenuDTO;
import Seguro.Dto.MenuitemDTO;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONException;
import org.json.JSONObject;
public class MenuitemCTR extends HttpServlet {
private MenuitemDTO dto;
private MenuitemDAO dao;
private MenuDTO menuDto;
private Gson gson;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
try {
PrintWriter out = response.getWriter();
System.out.println("Llegamos al controlador");
String cadenaJSON = Metodos_genericos.deRequestToJson(request);
JSONObject jsonObject = new JSONObject(cadenaJSON);//se convierte el JsonElement que viene de la cadena Json a JsonObject
Integer menuid;
gson = new Gson();
dto = gson.fromJson(cadenaJSON, MenuitemDTO.class);
dao = new MenuitemDAO();
menuDto = new MenuDTO();
// menuDto.setId(dto.getMenu());
System.out.println("bandera en CTR: " + dto.getBandera());
switch (dto.getBandera()) {
case 1:
menuid = jsonObject.getInt("menu_id");//se le asigna el valor de menu_id a una variable int
menuDto.setId(menuid);//se le setea al ID en menu_DTO
dto.setMenu(menuDto);//MenuDTO se le setea a setMenu
if (dao.agregar(dto)) {
// Operación Existosa => al cliente
} else {
// Operación Erronea => al cliente
}
break;
case 2:
menuid = jsonObject.getInt("menu_id");//se le asigna el valor de menu_id a una variable int
menuDto.setId(menuid);//se le setea al ID en menu_DTO
dto.setMenu(menuDto);
if (dao.modificar(dto)) {
// Operación Existosa => al cliente
} else {
// Operación Erronea => al cliente
}
break;
case 3:
if (dao.eliminar(dto)) {
// Operación Existosa => al cliente
} else {
// Operación Erronea => al cliente
}
break;
case 4:
String json = gson.toJson(dao.seleccionarSegunId(dto));
if (json != null) {
System.out.println("Json " + json);
response.setContentType("application/json, charset=UTF-8");
out.println("[" + json + "]");
out.close();
} else {
out.println("");
out.close();
}
break;
case 5:
response.setContentType("application/json, charset=UTF-8");
MenuDAO daoMenu = new MenuDAO();
String cadenaMenu = gson.toJson(daoMenu.seleccionarTodos());
if (cadenaMenu != null) {
//enviar al js la cadena
System.out.println("Cadena combo" + cadenaMenu);
out.println(cadenaMenu);
} else {
//enviar alguna respuesta para indicar error
}
break;
case 6:
//seleccionarTodos < menuitemsistema>
response.setContentType("application/json, charset=UTF-8");
String cadenaMenuItem = gson.toJson(dao.seleccionarTodos());
if (cadenaMenuItem != null) {
//enviar al js la cadena
System.out.println("Cadena Grilla" + cadenaMenuItem);
out.println(cadenaMenuItem);
out.close();
} else {
//enviar alguna respuesta para indicar error
}
break;
default:
throw new AssertionError();
}
} catch (JSONException ex) {
Logger.getLogger(MenuitemCTR.class.getName()).log(Level.SEVERE, null, ex);
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
As I explained, my problem is that when loading the page both functions are activated in the js but my flag variable is overwritten, I have already tried a method like calling one when loading the page and then calling the other after 30 seconds but the same way it continues to overwrite me. Thank you very much!