Search code examples
javascripthtmlajaxxmlhttprequest

insert data in new row in javascript


we get data with XMLHttpRequest from costume( mocki.io and fake json) url, I want to insert name and city in new tag! but in this code set all data element.name and element.city in one table row!! we should have 4 and in every tr tag we should have two td tags include name and city data.

can help me to set pair (name, city) in new table row?

thanks.

<html lang="en">
        <head>
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous">
            <meta charset="UTF-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>AJAX</title>
        </head>
        <body>
            <h1 style="text-align:center" id="data"></h1>
            <table id="table" class="table">
                <thead>
                    <tr>
                        <th>name</th>
                        <th>city</th>
                    </tr>
                </thead>
                <tbody>
                    <tr>
                        <td id="name"></td>
                        <td id="city"></td>
                    </tr>
                </tbody>
            </table>
        <script>
    
            // Create XML HTTP Request
            let xHTTP = new XMLHttpRequest();
            xHTTP.open('GET','https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8');
            xHTTP.onload = () => {
                if (xHTTP.status == 200 && xHTTP.readyState == 4){
                }
            }
            
            // Separeted Object Data
            function processResult(result){
                result.forEach(element => {
                    console.log(element);
                    console.log(element.name);
                    document.getElementById('name').innerHTML  +=  element.name + '</br>';
                    document.getElementById('city').innerHTML  +=  element.city + '</br>';
                });
            }
    
            // GET DATA from URL
            let response;
            xHTTP.onreadystatechange = function(){
                if (xHTTP.status == 200 && this.readyState == 4){
                    console.log('AJAX was succeed');
                    response = JSON.parse(this.response);
                    console.log('my response is: ',response);
                    console.log(typeof(response));
                    processResult(response); 
                }
            };
    
            // SEND Result to server
            xHTTP.send();
        </script>
    </body>
    </html>

<!-- begin snippet: js hide: false console: true babel: false -->


Solution

  • To be honest it was quite difficult to understand your question as the way you explained it.

    What i could understand is, that you are trying to display your fetched data correctly in your created table.

    Your Problem:

    You are facing a problem because you are changing the innerHTML of your <td> (table data) in plain text without wrapping it within a new <tr> (table row).

    To be more precise: You would need a new table row for every result (movie and name) to display the table correctly. Right now you are placing all of your result in just one <tr>with two <td> inside. To match your results you would need 4 <tr> with 2 <td> inside.

    Possible solution 1: Fast and supported by all Browser Versions

    The much easier way of ensuring that your table is displayed correctly (also for older Browser Versions), is to access your <tbody> directly and appending the new <tr>, <td> and your data within the .innerHTML of your <tbody> like this:

    <html lang="en">
      <head>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
          integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
          crossorigin="anonymous"
        />
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>AJAX</title>
      </head>
      <body>
        <h1 style="text-align: center" id="data"></h1>
        <table id="table" class="table">
          <thead>
            <tr>
              <th>Name</th>
              <th>City</th>
            </tr>
          </thead>
          <tbody id="tableData"></tbody>
        </table>
        <script>
          // Create XML HTTP Request
          let xHTTP = new XMLHttpRequest();
          xHTTP.open(
            "GET",
            "https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8"
          );
          xHTTP.onload = () => {
            if (xHTTP.status == 200 && xHTTP.readyState == 4) {
            }
          };
    
          // Separeted Object Data
          function processResult(result) {
            result.forEach((element, i) => {
              document.getElementById(
                "tableData"
              ).innerHTML += `<tr id="result${i}"><td id=MovieName${i}>${element.name}</td><td id=CityName${i}>${element.city}</td></tr>`;
            });
          }
    
          // GET DATA from URL
          let response;
          xHTTP.onreadystatechange = function () {
            if (xHTTP.status == 200 && this.readyState == 4) {
              response = JSON.parse(this.response);
              processResult(response);
            }
          };
    
          // SEND Result to server
          xHTTP.send();
        </script>
      </body>
    </html>
    
    <!-- begin snippet: js hide: false console: true babel: false -->

    Possible solution 2: This solution works, but is much slower.

    You could try to create a new table row with .createElement() for every result that you get from your request, append two new TextNodes (with .createTextNode) and then append your data (with .appendChild()) "movie" and "city" to two different <td> within the new created table row. Afterwards its quite easy to append the whole <tr> to your actual table to display the data correctly.

    If you would do it this way it could look something like this:

    <html lang="en">
      <head>
        <link
          rel="stylesheet"
          href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
          integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65"
          crossorigin="anonymous"
        />
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>AJAX</title>
      </head>
      <body>
        <h1 style="text-align: center" id="data"></h1>
        <table id="table" class="table">
          <thead>
            <tr>
              <th>Name</th>
              <th>City</th>
            </tr>
          </thead>
          <tbody id="tableData"></tbody>
        </table>
        <script>
          // Create XML HTTP Request
          let xHTTP = new XMLHttpRequest();
          xHTTP.open(
            "GET",
            "https://mocki.io/v1/d4867d8b-b5d5-4a48-a4ab-79131b5809b8"
          );
          xHTTP.onload = () => {
            if (xHTTP.status == 200 && xHTTP.readyState == 4) {
            }
          };
    
          // Separeted Object Data
          function processResult(result) {
            result.forEach((element) => {
              const tableRowNode = document.createElement("tr");
              const tableNodeMovie = document.createElement("td");
              const tableNodeCity = document.createElement("td");
              const movieTextNode = document.createTextNode(element.name);
              const cityTextNode = document.createTextNode(element.city);
              tableNodeMovie.appendChild(movieTextNode);
              tableNodeCity.appendChild(cityTextNode);
              tableRowNode.appendChild(tableNodeMovie);
              tableRowNode.appendChild(tableNodeCity);
              document.getElementById("tableData").appendChild(tableRowNode);
            });
          }
    
          // GET DATA from URL
          let response;
          xHTTP.onreadystatechange = function () {
            if (xHTTP.status == 200 && this.readyState == 4) {
              response = JSON.parse(this.response);
              processResult(response);
            }
          };
    
          // SEND Result to server
          xHTTP.send();
        </script>
      </body>
    </html>