Home > Back-end >  onclick get element from api and with how many row form input field by user
onclick get element from api and with how many row form input field by user

Time:07-06

Simple this i need to display this api "randomuser.me/api/?results=10" i table this job done, but i need use fill how row you need to display on the table and get the data from api ex : user put 10 get 10 row and display it on the table

  <H3>How Many Row You Need to Display Below ?</H3>
  <label for="fname">Please Enter Number (Max 100):</label>
  <input type="number" id="fname" name="fname" min="0" max="100"  />
  <input type="submit" value="Get Data" id="results" />
  
  <br>


  <!-- <div id="f5buddytable"></div> -->

</form>


<script>
 // https://randomuser.me/api/?results=10 to get 10 row

  var url = "https://randomuser.me/api/?";     
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.onload = function () {
    var users = JSON.parse(xhr.responseText);
    if (xhr.readyState == 4 && xhr.status == "200") {
      var table =
        "<table border='1'><tr><th> User Name</th><th>Email</th><th>Contact</th></tr>";
      var tr = "";
      var tableend = "</table>";
      var name, email, phone;
      for (var i = 0; i < users.results.length; i  ) {
        name =
          users.results[i]["name"]["title"]  
          " "  
          users.results[i]["name"]["first"];
        email = users.results[i]["email"];
        phone = users.results[i]["phone"];

        tr  =
          "<tr> <td>"  
          name  
          "</td> <td>"  
          email  
          "</td> <td>"  
          phone  
          "</td> </tr>";
      }
      var finaltable = table   tr   tableend;
      document.getElementById("f5buddytable").innerHTML = results   finaltable;
    } else {
      console.error(users);
    }
  };
  xhr.send(null);
</script>

Like this i need thank you enter image description here

CodePudding user response:

<form>
    <h3>How Many Row You Need to Display Below ?</h3>
    <label for="fname">Please Enter Number (Max 100):</label>
    <input type="number" id="fname" name="fname" min="0" max="100" />

    <input type="submit" value="Get Data" id="results" />

    <br />

    <div id="f5buddytable"></div>
</form>

<script>
    const queryString = Object.fromEntries(new URLSearchParams(window.location.search).entries());
    var numberOfRecords = queryString.fname;
    var url = 'https://randomuser.me/api/?results='   numberOfRecords;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url, true);
    xhr.onload = function () {
        var users = JSON.parse(xhr.responseText);
        if (xhr.readyState == 4 && xhr.status == '200') {
            var table = "<table border='1'><tr><th> User Name</th><th>Email</th><th>Contact</th></tr>";
            var tr = '';
            var tableend = '</table>';
            var name, email, phone;
            for (var i = 0; i < users.results.length; i  ) {
                name = users.results[i]['name']['title']   ' '   users.results[i]['name']['first'];
                email = users.results[i]['email'];
                phone = users.results[i]['phone'];

                tr  = '<tr> <td>'   name   '</td> <td>'   email   '</td> <td>'   phone   '</td> </tr>';
            }
            var finaltable = table   tr   tableend;
            document.getElementById('f5buddytable').innerHTML = finaltable; //REMOVED results, it was referencing the input submit
        } else {
            console.error(users);
        }
    };
    xhr.send(null);
</script>

CodePudding user response:

I don't know if I get you right, but I think you are asking for url parameter? https://developer.mozilla.org/en-US/docs/Web/API/Location/search You can get this in JS using this.

const queryString = window.location.search;

const urlParams = new URLSearchParams(queryString);

const page_type = urlParams.get('results')

console.log(results);

Then you add to html?

var newhtml = ""

for(var i=0; i<results; i  ){
  newhtml  = <div>SOME DIV</div>

}

document.getElementById("container").innerHtml = newhtml;

I can't post comment so I post answer.

CodePudding user response:

You can use fetch to get data, and use document.createElement() & append() to create and add rows to the table.

Here's an example:

explanation provided as comments

also You may dismiss the css part, i just added it to make it look better

const input = document.getElementById("input");
const getInput = document.getElementById("getInput");

const tbl = document.getElementById("tbl");
const status = document.getElementById("status");

getInput.addEventListener("click", () => {
  // gets value from input field
  const count = input.value;
  // check if taken value is 1-100
  if (input.value !== "" && count >= 1 && count <= 100) {
    // cleares the table
    tbl.innerHTML = "";
    // sets status message
    status.innerHTML = "Loading...";
    // send request to server to get data
    fetch(`https://randomuser.me/api/?results=${count}`)
      .then((response) => response.json())
      .then((data) => {
        results = data.results;
        // removes status message
        status.innerHTML = "";
        // creates table columns
        const tr = document.createElement("tr");
        ["Name", "Email", "Contact"].map((col) => {
          const th = document.createElement("th");
          th.innerText = col;
          tr.append(th);
        });
        tbl.append(tr);

        results.forEach((user) => {
          // creates <tr> (row) for each user
          const tr = document.createElement("tr");

          // creates <td> for [Name, Email, Contact] and values them with the taken values from server
          const nameHolder = document.createElement("td");
          nameHolder.innerText = `${user.name.title} ${user.name.first}`;
          const mailHolder = document.createElement("td");
          mailHolder.innerText = user.email;
          const contactHolder = document.createElement("td");
          contactHolder.innerText = user.cell;

          // appends generated <td> to our row
          tr.append(nameHolder, mailHolder, contactHolder);
          // finally appends the created row to the table
          tbl.append(tr);
        });
      });
  }
  // if taken value is not in range(1-100), clears input field and table
  else {
    alert("Entered number must be 1-100");
    input.value = "";
    tbl.innerHTML = "";
  }
});
body {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
  padding: 0;
  overflow-y: overlay;
  font-family: "Open Sans", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", Helvetica, Arial, sans-serif;
  background-image: radial-gradient(circle farthest-corner at 10% 20%, rgba(90, 92, 106, 1) 0%, rgba(32, 45, 58, 1) 81.3%);
}

.container {
  display: flex;
  flex-direction: column;
  background: white;
  padding: 15px;
  width: 80vw;
  border-radius: 10px;
  overflow: hidden;
}

.content {
  text-align: center;
  max-height: 500px;
  margin: 10px;
  overflow-y: auto;
}

#status {
  color: rgba(245, 116, 185, 1);
  font-size: 15pt;
}

.row {
  display: flex;
  align-items: center;
}

#input {
  width: 100px;
  padding: 8px;
}

#getInput {
  padding: 10px;
  border: none;
  margin: 0 5px;
  border-radius: 5px;
  color: white;
  background-image: linear-gradient(64.5deg, rgba(245, 116, 185, 1) 14.7%, rgba(89, 97, 223, 1) 88.7%);
  cursor: pointer;
}

table {
  width: 100%;
}

th {
  border: 1px solid black;
  padding: 5px;
  border-radius: 5px;
}

tr:not(tr:last-child) td {
  border-bottom: 1px solid gray;
}
<div >
  <h3>How Many Row You Need to Display Below ?</h3>
  <div >
    <label for>Please Enter Number(Max 100):</label>
    <input id="input" type="number" placeholder="1-100" min="1" max="100" />
    <button id="getInput">Get</button>
  </div>
  <div >
    <span id="status"></span>
    <table id="tbl"></table>
  </div>
</div>

CodePudding user response:

just wrap xhr code into function and call it on any button on submit.
i just add this snippet for you. this snippet not work in below editor, try on your screen.

function getData(results) {
  // https://randomuser.me/api/?results=10 to get 10 row
  var url = "https://randomuser.me/api/?";
  if (results) {
    url  = 'results='   results
  }
  var xhr = new XMLHttpRequest();
  xhr.open("GET", url, true);
  xhr.onload = function () {
    var users = JSON.parse(xhr.responseText);
    if (xhr.readyState == 4 && xhr.status == "200") {
      var table =
        "<table border='1'><tr><th> User Name</th><th>Email</th><th>Contact</th></tr>";
      var tr = "";
      var tableend = "</table>";
      var name, email, phone;
      for (var i = 0; i < users.results.length; i  ) {
        name =
          users.results[i]["name"]["title"]  
          " "  
          users.results[i]["name"]["first"];
        email = users.results[i]["email"];
        phone = users.results[i]["phone"];

        tr  =
          "<tr> <td>"  
          name  
          "</td> <td>"  
          email  
          "</td> <td>"  
          phone  
          "</td> </tr>";
      }
      var finaltable = table   tr   tableend;
      document.getElementById("f5buddytable").innerHTML = results   finaltable;
    } else {
      console.error(users);
    }
  };
  xhr.send(null);
}

getData();
<!DOCTYPE html>
<html lang="en">

<head>
  <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>Document</title>
  <style>
    body {
      background-color: olive;
      /* width: 100%; */
      height: 100%;
    }
  </style>
  <style>
  </style>

</head>

<body>
  <!DOCTYPE html>
  <html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://code.jquery.com/jquery-3.5.0.js"></script>
    <script type="text/javscript" src="script.js"></script>
    <link rel="stylesheet" href="Style.css">
    <title>Test Sample</title>
  </head>

  <h1>Sample</h1>

  <body>
    <H3>How Many Row You Need to Display Below ?</H3>
  <label for="fname">Please Enter Number (Max 100):</label>
  <input type="number" id="fname" name="fname" min="0" max="100"  />
  <input type="submit" value="Get Data" id="results" onclick="getData(document.getElementById('fname').value)"/>
  
  <br>
  <div id="f5buddytable"></div>
  </body>

  </html>
</body>

</html>

  • Related