AJAX Node.js

Last Updated:

AJAX Node.js

In the following example, we will create an interactive application to find the details of the user-specified continent by using Node.js.

Example

The following is the server-side coding using Node.js.

continent-json.js
var express = require("express"); var app = express(); app.post("/continent-json.js",function(req, res){ var obj = {population:"",area:"",countries:""}; switch(req.body.data){ case "Africa": obj.population = "121.61 crores"; obj.area = "30.37 million km²"; obj.countries = "Nigeria, South Africa, Egypt"; break; case "Oceania": obj.population = "2.46 crores"; obj.area = "7.692 million km²"; obj.countries = "Fiji, Guam, Palau"; break; case "Asia": obj.population = "446.1 crores"; obj.area = "44.58 million km²"; obj.countries = "Japan, Singapore, china"; break; case "Europe": obj.population = "74.14 crores"; obj.area = "10.18 million km²"; obj.countries = "Russia, Germany, UK"; break; } res.send(obj); }); app.listen(8000, function(){ console.log("port is listening to 8000"); });

The following is the client-side coding for user interaction.

HTML Online Compiler
<!DOCTYPE html> <html lang="en-US"> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <style> table, td, th{ border: 1px solid black; padding: 10px 5px; } table{ width: 100%; border-collapse: collapse; margin-top: 20px; } table tr th{ width: 150px; } </style> </head> <body> <h1>AJAX example using Node.js</h1> <p>Select any continent for details</p> <select> <option>Africa</option> <option>Asia</option> <option>Europe</option> <option>Oceania</option> </select> <div id="point"></div> <script> $(document).ready(function(){ $("select").change(function(){ $.post("/continent-json.js",{ data: $("select").val() },function(data){ // Create table on fly var myTable = "<table><tbody><tr><th>Population</th><td>"+data.population+"</td></tr><tr><th>Area</th><td>"+data.area+"</td></tr><tr><th>top countries</th><td>"+data.countries+"</td></tr></tbody></table>"; $("#point").html(myTable); }); }); // Trigger change() method only when the page load/refreshed $("select").trigger("change"); }); </script> </body> </html>

Share this Page

Meet the Author