JavaScript JSON HTML
JavaScript Basics

JavaScript JSON HTML

JSON and HTML

JSON can easily be translated into JavaScript, and JavaScript can be used to create HTML in your web pages.

HTML Table

Create an HTML table with data received as JSON:

Example:

const dbParam = JSON.stringify({table: "customers", limit: 20});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let text = "<table border='1'>";
  for (let x in myObj) {
    text += "<tr><td>" + myObj[x].name + "</td></tr>";
  }
  text += "</table>";
  document.getElementById("demo").innerHTML = text;
};
xmlhttp.open("POST", "json_demo_html_table.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

Dynamic HTML Table

Create an HTML table based on the value of a dropdown menu:

Example:

<select id="myselect" onchange="changeMySelect(this.value)">
  <option value="">Choose an option:</option>
  <option value="customers">Customers</option>
  <option value="products">Products</option>
  <option value="suppliers">Suppliers</option>
</select>

<script>
function changeMySelect(sel) {
  const dbParam = JSON.stringify({table: sel, limit: 20});
  const xmlhttp = new XMLHttpRequest();
  xmlhttp.onload = function() {
    const myObj = JSON.parse(this.responseText);
    let text = "<table border='1'>";
    for (let x in myObj) {
      text += "<tr><td>" + myObj[x].name + "</td></tr>";
    }
    text += "</table>";
    document.getElementById("demo").innerHTML = text;
  };
  xmlhttp.open("POST", "json_demo_html_table.php");
  xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
  xmlhttp.send("x=" + dbParam);
}
</script>

HTML Drop Down List

Create an HTML drop-down list with data received as JSON:

Example:

const dbParam = JSON.stringify({table: "customers", limit: 20});
const xmlhttp = new XMLHttpRequest();
xmlhttp.onload = function() {
  const myObj = JSON.parse(this.responseText);
  let text = "<select>";
  for (let x in myObj) {
    text += "<option>" + myObj[x].name + "</option>";
  }
  text += "</select>";
  document.getElementById("demo").innerHTML = text;
};
xmlhttp.open("POST", "json_demo_html_table.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);

This content explains how to create HTML tables and dropdown lists using data received as JSON, providing examples for each scenario.

Take a look into your desired course