Get ExpressJS data from HTML File Using AJAX

Before Started


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:


How to do that … ?


  • 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){


__dirname is for getting directory name besause sendFile need absolute path

Create HTML File

Create home.html file and add this code below:

<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+=data[idx].id +"</td><td>"+data[idx].quantity+"</td></tr>";
	 document.getElementById("dataHasil").innerHTML = str
  };"GET", "/data_stock_masuk", true);

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



  • 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


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 *