JSP AJAX Example

In this tutorial, we are using JSP as a server-side programming language. In the below example, we simply print the response received from the server.

Example.html

When you click on Show Details button, fetch() function will be called. In the fetch() function, we have return AJAX coding. Once we get the response from the server, we displayed it in the div element having id equal to mobiles.

<!DOCTYPE html>
<html>
   <head>
      <script>
         function fetch(){
	    var request = new XMLHttpRequest();
	    request.onreadystatechange = function(){
	       if(this.readyState == 4 && this.status == 200){
	          var response = this.responseText;
		  document.getElementById("mobiles").innerHTML=response;
	       }
            };
            request.open("GET", "details.jsp", true);
	    request.send();
         }
      </script>
   </head>
   <body>
      <button onclick="fetch()">Show Details</button>
      <div id="mobiles"></div>
   </body>
</html>

details.jsp

<%    
    out.print("Name: Samsung Galaxy J7<br />");
    out.print("Price: 15500<br />");    
    out.print("Screen Size: 5.5<br />");
    out.print("Operating System: Android 6.0<br />");
%>