Get ExpressJS data from HTML File Using AJAX

Before Started

Wanted

After i have get MySQL data Using ExpressJS then i want to display the Navigation menu like left image below and if i click “Ambil Data” then data will be displayed in a table like the right image below:

Question:

How to do that … ?

Answer:

  • Add route for displaying navigation menu
  • Add route for displaying HTML file
  • Add AJax Script in HTML file to get the data from ExpressJS

Navigation Menu Route

Open file index.js and add this code:

app.get('/menu', function(req, res){
   res.send("<a href='/ambilData'>Ambil Data</a>");
});

HTML File Route

Add this code to index.js file:

app.get('/ambilData', function(req, res){
   res.sendFile(__dirname+"/home.html");
});

Explain:

__dirname is for getting directory name besause sendFile need absolute path

Create HTML File

Create home.html file and add this code below:

<html>
<head>
<script type="text/javascript">
var xhttp = new XMLHttpRequest();
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
	 let json=JSON.parse(this.responseText)
	 let data=json.data_stock;
   	 let str='<table border=1><tr><th>id</th><th>Quantity</th></tr>';
	 for(var idx = 0; idx < data.length; idx++) {
		str+="<tr><td>";
		str+=data[idx].id +"</td><td>"+data[idx].quantity+"</td></tr>";
	 
	 }
	 str+="</table>";
	 document.getElementById("dataHasil").innerHTML = str
    }
  };
  xhttp.open("GET", "/data_stock_masuk", true);
  xhttp.send();
</script>

<head>
<body>
<div id="dataHasil"></div>

</body>
</html>

Explain

  • JSON.parse(this.responseText) for convert text to JSON
  • json.data_stock for getting data_stock object from json object
  • data[idx].id for getting id value from data object with index array of idx

Result

Open your browser and type “http://localhost:3000/menu”

Thanks for reading

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *