skip to Main Content

I have a web page and a servlet. I create input elements dynamically with using javascript in webpage. The servlet is back-end that evaluate some mathematical calculations. I am getting the data to send to servlet from dynamically created input elements. These input elements id’s are also been creating dynamically. I am able to retrieve data and create the elements without any error.

But, I want to evaluate some mathematical operations in servlet then send to result to an ‘result’ textbox in the webpage. So I don’t want to refresh the web page. Beacause the ‘result’ id textbox is also been creating dynamically.

The related html code.

<form action="/TYT_Mat_Soru_Cozumu_Java_war_exploded/Servlet/HesaplamaIslemleri" method="post" id="sayilarForm">
      <input type="hidden" name="grupNoTutan" id="grupNoTutan"></input>
    </form>

The code that dynamically create input elements.

  function sayiEklemeKutular(operatorTipi){
  var satir_1Div = document.createElement("div");
  satir_1Div.setAttribute("class", "row");
  satir_1Div.setAttribute("id", grup_no + "_satir_1");
  var satir_2Div = document.createElement("div");
  satir_2Div.setAttribute("class", "row");
  var satir_3Div = document.createElement("div");
  satir_3Div.setAttribute("class", "row");
  var satir_4Div = document.createElement("div");
  satir_4Div.setAttribute("class", "row");
  var satir_5Div = document.createElement("div");
  satir_5Div.setAttribute("class", "row");

  var node = "";
  switch (operatorTipi) {
    case "+":
      node = document.createTextNode('+');
      break;
    case "-":
      node = document.createTextNode('-');
      break;
    case "*":
      node = document.createTextNode('*');
      break;
    case "/":
      node = document.createTextNode('/');
      break;
    case "√":
      node = document.createTextNode('√');
      break;
    case "0/":
      node = document.createTextNode('0/');
      break;
    case "^√==":
      node = document.createTextNode('^√==');
      break;
    case "^==":
      node = document.createTextNode('^==');
      break;
    default:
      node = document.createTextNode('Hata');
  }
  satir_3Div.appendChild(node);
  satir_3Div.style.textAlign = "center";
  satir_3Div.style.fontSize = "14pt";
  satir_3Div.style.fontColor = "#ffffff";

  var satir_2_sutun_1Div = document.createElement("div");
  var satir_2_sutun_2Div = document.createElement("div");
  var satir_2_sutun_3Div = document.createElement("div");
  satir_2_sutun_1Div.setAttribute("class", "col");
  satir_2_sutun_2Div.setAttribute("class", "col");
  satir_2_sutun_3Div.setAttribute("class", "col");

  var satir_4_sutun_1Div = document.createElement("div");
  var satir_4_sutun_2Div = document.createElement("div");
  var satir_4_sutun_3Div = document.createElement("div");
  satir_4_sutun_1Div.setAttribute("class", "col");
  satir_4_sutun_2Div.setAttribute("class", "col");
  satir_4_sutun_3Div.setAttribute("class", "col");

  var satir_5_sutun_1Div = document.createElement("div");
  var satir_5_sutun_2Div = document.createElement("div");
  var satir_5_sutun_3Div = document.createElement("div");
  satir_5_sutun_1Div.setAttribute("class", "col");
  satir_5_sutun_2Div.setAttribute("class", "col");
  satir_5_sutun_3Div.setAttribute("class", "col");

  var kokDerece1 = document.createElement("input");
  var kokKatsayi1 = document.createElement("input");
  var kokIciDeger1 = document.createElement("input");

  kokDerece1.setAttribute("name", grup_no + "_kokDerecesi_" + komponent_no);
  kokDerece1.setAttribute("id", grup_no + "_kokDerecesi_" + komponent_no);
  kokDerece1.setAttribute("class", "form-control");
  kokDerece1.setAttribute("type", "text");
  kokDerece1.setAttribute("placeholder", "Kökün Derecesi");

  kokIciDeger1.setAttribute("name", grup_no +  "_kokIciDeger_" + komponent_no);
  kokIciDeger1.setAttribute("id", grup_no + "_kokIciDeger_" + komponent_no);
  kokIciDeger1.setAttribute("class", "form-control");
  kokIciDeger1.setAttribute("type", "text");
  kokIciDeger1.setAttribute("placeholder", "Kök İçindeki Değer");

  kokKatsayi1.setAttribute("name", grup_no +  "_kokKatsayi_" + komponent_no);
  kokKatsayi1.setAttribute("id", grup_no + "_kokKatsayi_"+ komponent_no);
  kokKatsayi1.setAttribute("class", "form-control");
  kokKatsayi1.setAttribute("type", "text");
  kokKatsayi1.setAttribute("placeholder", "Kökün Katsayısı");

  komponent_no = komponent_no + 1;

  var kokDerece2 = document.createElement("input");
  var kokIciDeger2 = document.createElement("input");
  var kokKatsayi2 = document.createElement("input");

  kokDerece2.setAttribute("name", grup_no + "_kokDerecesi_" + komponent_no);
  kokDerece2.setAttribute("type","text");
  kokDerece2.setAttribute("id", grup_no + "_kokDerecesi_" + komponent_no);
  kokDerece2.setAttribute("class", "form-control");
  kokDerece2.setAttribute("placeholder", "Kökün Derecesi");

  kokIciDeger2.setAttribute("name", grup_no +  "_kokIciDeger_" + komponent_no);
  kokIciDeger2.setAttribute("type", "text");
  kokIciDeger2.setAttribute("id", grup_no + "_kokIciDeger_" + komponent_no);
  kokIciDeger2.setAttribute("class", "form-control");
  kokIciDeger2.setAttribute("placeholder", "Kök İçindeki Değer");

  kokKatsayi2.setAttribute("name", grup_no + "_kokKatsayi_" + komponent_no);
  kokKatsayi2.setAttribute("type","text");
  kokKatsayi2.setAttribute("id", grup_no + "_kokKatsayi_"+ komponent_no);
  kokKatsayi2.setAttribute("class", "form-control");
  kokKatsayi2.setAttribute("placeholder", "Kökün Katsayısı");

  var sonucInput = document.createElement("INPUT");
  sonucInput.setAttribute("class", "form-control");
  sonucInput.setAttribute("name", grup_no + "_sonuc");
  sonucInput.setAttribute("id", grup_no + "_sonuc");
  sonucInput.setAttribute("placeholder", "Sonuç");

  var silButon = document.createElement("BUTTON");
  silButon.setAttribute("class", "btn btn-danger");
  silButon.setAttribute("name", grup_no + "_silButon");
  silButon.textContent = "Grubu Sil";
  silButon.setAttribute("onclick", 'silButonununGrupNosunuGetir(this.getAttribute("name"))');


  var hesaplaButon = document.createElement("BUTTON");
  hesaplaButon.setAttribute("class", "btn btn-success");
  hesaplaButon.setAttribute("type", "submit");
  hesaplaButon.setAttribute("name", grup_no + "_hesaplaButon");
  hesaplaButon.setAttribute("onclick", 'ismiHiddenaEkle(this.getAttribute("name"))');
  hesaplaButon.textContent = "Hesapla";

  komponent_no = 1;
  grup_no = grup_no + 1;

  satir_2_sutun_1Div.appendChild(kokDerece1);
  satir_2_sutun_2Div.appendChild(kokKatsayi1);
  satir_2_sutun_3Div.appendChild(kokIciDeger1);

  satir_2Div.appendChild(satir_2_sutun_1Div);
  satir_2Div.appendChild(satir_2_sutun_2Div);
  satir_2Div.appendChild(satir_2_sutun_3Div);

  satir_4_sutun_1Div.appendChild(kokDerece2);
  satir_4_sutun_2Div.appendChild(kokKatsayi2);
  satir_4_sutun_3Div.appendChild(kokIciDeger2);

  satir_4Div.appendChild(satir_4_sutun_1Div);
  satir_4Div.appendChild(satir_4_sutun_2Div);
  satir_4Div.appendChild(satir_4_sutun_3Div);

  satir_5_sutun_1Div.appendChild(sonucInput);
  satir_5_sutun_2Div.appendChild(silButon);
  satir_5_sutun_3Div.appendChild(hesaplaButon);

  satir_5Div.appendChild(satir_5_sutun_1Div);
  satir_5Div.appendChild(satir_5_sutun_2Div);
  satir_5Div.appendChild(satir_5_sutun_3Div);

  satir_1Div.appendChild(satir_2Div);
  satir_1Div.appendChild(satir_3Div);
  satir_1Div.appendChild(satir_4Div);
  satir_1Div.appendChild(satir_5Div);

  satir_1Div.style.marginTop = '30px';
  satir_3Div.style.marginTop = '10px';
  satir_4Div.style.marginTop = '10px';
  satir_5Div.style.marginTop = '10px';

  satir_1Div.style.backgroundColor = "#18A2D9";
  satir_1Div.style.padding = "10px";
  satir_1Div.style.borderRadius = "2em";

  var formId = document.getElementById("sayilarForm");
  formId.appendChild(satir_1Div);
}

The code that add sequence number of created dynamically element to a hidden element and calling the Ajax code.

    function ismiHiddenaEkle(name){
          var hiddenEleman = document.getElementById("grupNoTutan");
          hiddenEleman.value = name;
          hesaplaServleteGonder();
        }
    
    The Javascript code that contain Ajax.
    
        function hesaplaServleteGonder(){
        var butonAdi= document.getElementById("grupNoTutan").value;
        var grup_no = butonAdi.charAt(0);
        var i = 1;
    
        var birinciKokDerecesi;
        var birinciKatsayi;
        var birinciKokIciDeger;
    
        var ikinciKokDerecesi;
        var ikinciKatsayi;
        var ikinciKokIciDeger;
        var sonuc;
        birinciKokDerecesi = document.getElementById(grup_no + "_kokDerecesi_" + i).value;
        birinciKatsayi = document.getElementById(grup_no + "_kokKatsayi_" + i).value;
        birinciKokIciDeger = document.getElementById(grup_no + "_kokIciDeger_" + i).value;
        sonuc = document.getElementById(grup_no + "_sonuc");
        i= i + 1;
        ikinciKokDerecesi = document.getElementById(grup_no + "_kokDerecesi_" + i).value;
        ikinciKatsayi = document.getElementById(grup_no + "_kokKatsayi_" + i).value;
        ikinciKokIciDeger = document.getElementById(grup_no + "_kokIciDeger_" + i).value;
        i = 1;
        $.ajax({
          type:'POST',
          url:'/TYT_Mat_Soru_Cozumu_Java_war_exploded/Servlet/HesaplamaIslemleri',
          dataType: 'json',
          contentType:'application/json',
          data:  $('#sayilarForm').serialize() ,
          cache:false,
          success:function(data){
            alert(data);
            $('#sonuc').text(responseText);
          },
          error:function(){
            alert('error');
          }
        });
    }

The servlet is below.

@WebServlet("/Servlet/HesaplamaIslemleri")
public class HesaplamaIslemleri extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        PrintWriter out = resp.getWriter();

        StringBuilder sb = new StringBuilder();
        BufferedReader br = req.getReader();
        String str;
        while( (str = br.readLine()) != null ){
            sb.append(str);
        }
        System.out.println(sb.toString());
        resp.getWriter().print(sb.toString());
    }
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        doPost(req,resp);
    }

}

When i click the button , a new page is loading and there are values with their names in the page.
Like this grupNoTutan=1_hesaplaButon&1_kokDerecesi_1=2&1_kokKatsayi_1=4&1_kokIciDeger_1=2&1_kokDerecesi_2=2&1_kokKatsayi_2=8&1_kokIciDeger_2=2&1_sonuc=&1_hesaplaButon=

Can anyone help?

2

Answers


  1. Chosen as BEST ANSWER

    I solved the problem with that way. Servlet and javascript codes are below. Firstly, I breaked into pieces the json data to understand the structure. Then, I proccessed the data according to the which portion is array and which portion is object. (Created dynamically elements sequence number is storing in hidden element that named('grupNoTutan')

    Javascript:

      //Read the content of elements that created dynamically
      var butonAdi= document.getElementById("grupNoTutan").value;
      var grup_no = butonAdi.charAt(0);
      var i = 1;
    
      var birinciKokDerecesi;
      var birinciKatsayi;
      var birinciKokIciDeger;
    
      var ikinciKokDerecesi;
      var ikinciKatsayi;
      var ikinciKokIciDeger;
      var sonuc;
      var operator = document.getElementById("operator").textContent;
      //var url = "#" +  grup_no + "_kokDerecesi_" + i
      //var textboxvalue = $("'" + url + "'").val();
      var birKokD = grup_no + "_kokDerecesi_" + i;
      var birKokK = grup_no + "_kokKatsayi_" + i;
      var birKokID = grup_no + "_kokIciDeger_" + i;
      birinciKokDerecesi = document.getElementById(grup_no + "_kokDerecesi_" + i).value;
      birinciKatsayi = document.getElementById(grup_no + "_kokKatsayi_" + i).value;
      birinciKokIciDeger = document.getElementById(grup_no + "_kokIciDeger_" + i).value;
      sonuc = document.getElementById(grup_no + "_sonuc");
      i= i + 1;
      var ikiKokD = grup_no + "_kokDerecesi_" + i;
      var ikiKokK = grup_no + "_kokKatsayi_" + i;
      var ikiKokID = grup_no + "_kokIciDeger_" + i;
      ikinciKokDerecesi = document.getElementById(grup_no + "_kokDerecesi_" + i).value;
      ikinciKatsayi = document.getElementById(grup_no + "_kokKatsayi_" + i).value;
      ikinciKokIciDeger = document.getElementById(grup_no + "_kokIciDeger_" + i).value;
      i = 1;
    
      //send request to server
      let url = '/TYT_Mat_Soru_Cozumu_Java_war_exploded/Servlet/HesaplamaIslemleri';
      let xhr = new XMLHttpRequest();
      xhr.open("POST", url, true);
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencode");
      var data;
      data = JSON.stringify({
        "birinci":[{
        birKokD: birinciKokDerecesi,
        birKokK: birinciKatsayi,
        birKokID: birinciKokIciDeger}],
    
        "ikinci":[{
        ikiKokD: ikinciKokDerecesi,
        ikiKokK: ikinciKatsayi,
        ikiKokID: ikinciKokIciDeger
      }],"operator": operator
      });
      xhr.send(data);
      xhr.onload = function(){
       sonuc.readOnly = true
        sonuc.value = xhr.responseText;
      }
    

    Servlet Codes :

                // Business Logic
                KokluSayiIslemleriImpl business = new KokluSayiIslemleriImpl();
        
                // Reading Request Header
                StringWriter writer = new StringWriter();
                StringBuilder buffer = new StringBuilder();
                BufferedReader reader = req.getReader();
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line);
                }
                String data = buffer.toString();
                JSONObject jsonObj = new JSONObject(new String(data));
        
                // Creating the first object with data that getting from header
                JSONArray birinci = new JSONArray();
                birinci.put(jsonObj.get("birinci"));
                JSONObject birinciSayi = birinci.getJSONArray(0).getJSONObject(0);
                int kokDerecesi_1 = Integer.parseInt(birinciSayi.getString("birKokD"));
                double kokIciDeger_1 = Double.parseDouble(birinciSayi.getString("birKokID"));
                int kokKatsayi_1 = Integer.parseInt(birinciSayi.getString("birKokK"));
                KokluSayi koklusayi_1 = new KokluSayi(kokDerecesi_1,kokIciDeger_1,kokKatsayi_1);
                // Veri Sırası Test
                System.out.println(koklusayi_1.getKokDerecesi() + " / " + koklusayi_1.getKatsayi() + " / " + koklusayi_1.getKokIciDeger());
        
                // Creating the second object with data that getting from header
                JSONArray ikinci = new JSONArray();
                ikinci.put(jsonObj.get("ikinci"));
                JSONObject ikinciSayi = ikinci.getJSONArray(0).getJSONObject(0);
                int kokDerecesi_2 = Integer.parseInt(ikinciSayi.getString("ikiKokD"));
                double kokIciDeger_2 = Double.parseDouble(ikinciSayi.getString("ikiKokID"));
                int kokKatsayi_2 = Integer.parseInt(ikinciSayi.getString("ikiKokK"));
                KokluSayi koklusayi_2 = new KokluSayi(kokDerecesi_2,kokIciDeger_2,kokKatsayi_2);
                // Veri Sırası Test
                System.out.println(koklusayi_2.getKokDerecesi() + " / " + koklusayi_2.getKatsayi() + " / " + koklusayi_2.getKokIciDeger());
        
                // Getting the operator(which operation will processing)
                char operator = jsonObj.getString("operator").charAt(0);
        
                KokluSayi sonuc = business.dortIslem(koklusayi_1,koklusayi_2,operator);
                //send result back to client 
    resp.getWriter().write("D :" + sonuc.getKokDerecesi() + " - " + "K :" + sonuc.getKatsayi() + " - " + "D :" + sonuc.getKokIciDeger());
    

    Edit: Add reading content of elements that created dynamically code portion


  2. Firstly, the POST request you are making to your HTTP Resource is not AJAX. If you want to asynchronously make an HTTP Request, get the response and write to DOM without full page refresh, please check out the classic XmlHttpRequest first and research about other methods. On a high level, your task will go something like this,

    1. Construct the UI portion in JavaScript, if you want to do something dynamic.

    2. For Static portions, use a separate CSS file and move your styling to it. Don’t create all HTML elements and CSS Styling in JavaScript unless you need everything to be dynamic.

    3. Understand what you want to return from your server side.

    Do you want to return formatted HTML directly from server side? Or return data in formats like JSON or XML and get hold of returned AJAX response in client and manipulate the DOM (in your case the ‘result’ text box).

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search