Categories: Java

Code Example – How to Make AJAX Calls with Java Spring MVC

This article is aimed to provide quick code samples to rookies who would like to quickly get started with AJAX while working with Spring MVC based web application. In example below, the AJAX call is made on form submit to retrieve data from server and process it further.

Step 1: Get JQuery Library

Download JQuery library and place it in JS folder within one of your web assets folder. Even simpler, include following google script code and you are all set.

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

 

Step 2: Create a Form

Create a form such as following that would be dealt in this example.


<form id="sampleForm" method="post" action="/profile">
     

<div>
         <input type="text" name="firstname" id="firstname">
     </div>


     

<div>
         <input type="text" name="lastname" id="lastname">
     </div>


     

<div>
         <button type="submit" name="submit">Submit</button>
     </div>


</form>



 

Step 3: Create AJAX Code

Step 3 is about creating AJAX code on UI side that would send the request to server. Following is the sample code that needs to be placed within code.

$(document).ready(function() {
 $('#sampleForm').submit(
  function(event) {
   var firstname = $('#firstname').val();
   var lastname = $('#lastname').val();    
   var data = 'firstname='
     + encodeURIComponent(firstname)
     + '&amp;lastname='
     + encodeURIComponent(lastname);
   $.ajax({
    url : $("#sampleForm").attr("action"),
    data : data,
    type : "GET",

    success : function(response) {
     alert( response );
    },
    error : function(xhr, status, error) {
     alert(xhr.responseText);
    }
   });
   return false;
  });
 });

 

Step 4: Create Server-side Code

Last step is about creating server-side code that would recieve AJAX request, process it and send back the response. Following is the code which should be defined within a controller:

package com.vitalflux.sample;

@Controller
public class SomeController {

@RequestMapping(value = "/profile", method = RequestMethod.GET)
public @ResponseBody String processAJAXRequest(
   @RequestParam("firstname") String firstname,
   @RequestParam("lastname") String lastname ) {
  String response = "";
  // Process the request
  // Prepare the response string
  return response;
 }
}

Make sure that you included following in spring-servlet.xml. Note that package name of above controller is same as that mentioned below:

<context:component-scan base-package="com.vitalflux.sample" />


 

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking.

View Comments

Recent Posts

Retrieval Augmented Generation (RAG) & LLM: Examples

Last updated: 25th Jan, 2025 Have you ever wondered how to seamlessly integrate the vast…

1 week ago

How to Setup MEAN App with LangChain.js

Hey there! As I venture into building agentic MEAN apps with LangChain.js, I wanted to…

2 weeks ago

Build AI Chatbots for SAAS Using LLMs, RAG, Multi-Agent Frameworks

Software-as-a-Service (SaaS) providers have long relied on traditional chatbot solutions like AWS Lex and Google…

2 weeks ago

Creating a RAG Application Using LangGraph: Example Code

Retrieval-Augmented Generation (RAG) is an innovative generative AI method that combines retrieval-based search with large…

3 weeks ago

Building a RAG Application with LangChain: Example Code

The combination of Retrieval-Augmented Generation (RAG) and powerful language models enables the development of sophisticated…

3 weeks ago

Building an OpenAI Chatbot with LangChain

Have you ever wondered how to use OpenAI APIs to create custom chatbots? With advancements…

3 weeks ago