Tips on accessing the returned value from the controller within a JSP page using Ajax

This is a snippet of my JavaScript code:

 <script type="text/javascript">
        function callMe() {
            var districtId = $("#district").val();
            alert(districtId);
            $.ajax({
                type: "POST",
                url: "addBranch",
                data: "districtId=" + districtId,
                success: function(response) {



                }
            });
        }

    </script> 

Here is a portion of my controller code:

@RequestMapping(value = "/addBranch", method = RequestMethod.POST)
public @ResponseBody 
List getForm1(@ModelAttribute Branch branch, Model model,@RequestParam("districtId")    
int districtId) {
    try {

       districtVillageList = villageService.getDistrictVillageList(districtId);

    } catch (Exception er) {
        log.error("error in addLoanType=" + er);
    }
    return districtVillageList;
 }

Although I am successfully getting the list in the controller, I am unsure how to retrieve and utilize the values in my JSP file using Ajax. As I am new to working with Ajax, I would greatly appreciate any help on this matter. Thank you!

Answer №1

Once the list is returned in the controller, you can access it from the response and iterate through it using a for-in loop, like so:

<script type="text/javascript>
        function processList() {
            var districtId = $("#district").val();
            alert(districtId);
            $.ajax({
                type: "POST",
                url: "addBranch",
                data: "districtId=" + districtId,
                success: function(response) {
                       for (var i in response){
                       // response[i].performAction()
                      }   
                    }
            });
        }    
    </script> 

Consider using JSON objects to send the response instead of a list. For more information, check out these resources: jquery loop on Json data using $.each and jQuery loop over JSON result from AJAX Success?

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retain values of JavaScript variables acquired by their IDs even after a page refresh

I have a JavaScript function that retrieves HTML input values and inserts them into a table. However, when I refresh the page, those values are reset to null. How can I prevent this and keep the values visible after a refresh? I believe setting and getting ...

If I click on a different VueJS menu, make sure to close the current menu

When using a component menu, each item is displayed independently. However, I would like the open items to close automatically when I click on another item with the menu. I employ a toggle functionality on click to control the opening and closing of the c ...

Verify the fonts that are functioning correctly

Despite using the "dancing script" Google webfont and adding it through @font-face, font-family, I am unable to see it in the browser. I would like to know how to determine which fonts are correctly uploaded and rendering properly while viewing a website ...

A guide on how to implement promise return in redux actions for react native applications

I'm using redux to handle location data and I need to retrieve it when necessary. Once the location is saved to the state in redux, I want to return a promise because I require that data for my screen. Here are my actions, reducers, store setup, and ...

Verifying website responsiveness using Puppeteer

Looking to create a script that can determine if a webpage has a responsive design? Wondering how to go about it? Well, it's quite simple. In responsive websites, elements like divs, spans, footers, headers, and sections typically adjust to fit the s ...

Tips for configuring page-specific variables in Adobe DTM

Although I have integrated Adobe Analytics for tracking on my website, I am facing difficulty in properly defining the variables. This is how I attempted to define the variable: var z = new Object(); z.abc = true; z.def.ghi = true Despite following the ...

Struggling to effectively use XPath to target LI elements that contain specific text

Below is the HTML code for the list item in question: <li class="disabled-result" data-option-array-index="1" style="">4" (0)</li> Here is my attempt at using JavaScript to hide this list item, but it's not working as expected: var xpat ...

"Composing perfect sentences: The art of incorporating quotes

I am attempting to include text with quotes in a DIV, like so: "All is well that ends well" The text is generated dynamically and I'm using a JavaScript font replacement plugin (CUFON) to add quotes around the text. Sometimes, the ending quote drops ...

What are the steps to create custom Typescript RecursiveOmit and RecursivePick declarations for efficient cloning routines?

For some time now, I have been attempting to create a declaration for RecursiveOmit and RecursivePick in cloning methods such as JSON.parse(JSON.stringify(obj, ['myProperty'])) type RecursiveKey<T> = T extends object ? keyof T | RecursiveKe ...

What is the best way to transform JSON or an array from an AJAX responseText into a JavaScript array?

I recently implemented ajax into my code, and it is working perfectly. It provides me with either JSON or an array as the output. Here is the snippet of code I used: xmlhttp=new XMLHttpRequest(); xmlhttp.open("GET","http://map_ajax_control.php",false); xm ...

Is limiting the length of a URL string an effective strategy for enhancing security measures?

In my current setup, I have ColdFusion 8 and jQuery version 1.7.2. Utilizing CFAJAXPROXY to transmit data to a CFC generates a JSON array (argument collection) that is passed through the URL. Due to the substantial amount of data being transferred, the st ...

Populate the table with JSON content using jQuery

I am attempting to populate a table with JSON data using jQuery, but the content within the div remains empty. I need assistance in identifying the error. The array list contains the data (I verified this using console.log(list)). Additionally, list[' ...

emphasizing the specific text being searched for within the page

Looking for a solution to search values and highlight matching text words on a page? Let me help you with that. $(function() { var tabLinks = $('.nav > li'), tabsContent = $('.tab-content > div'), ...

Learn how to incorporate an input field into a form using the same class name

I am facing a challenging JavaScript issue that I have been struggling to resolve. My predicament involves a dynamically formed table with form fields. Here is the code snippet in question: var table = document.getElementById("table"); var row = table. ...

Dealing with asynchronous requests in Axios: A guide to solving the challenge

I'm working on a page named _id.vue in my Nuxt.js project: <template> <div class="wrapper"> <HeaderApp> <DivHeaderMenu> </DivHeaderMenu> </HeaderApp> <CenterContentDinamicFirmeni ...

The TypeScript optional callback parameter is not compatible with the anonymous function being passed to it

Encountering an issue with TS callbacks and function signatures. Here is my scenario: ... //inside a class //function should accept a callback function as parameter refreshConnection(callback?: Function) { //do something //then ca ...

An unexpected problem with text redirection that should not be happening

I am facing an issue with my HTML text field and post button on my website. Whenever I click the post button to make a post, it redirects to a separate PHP file called post.php which handles PHP and MySQL code for posting. However, I want to avoid this red ...

Adjust the color of an SVG icon depending on its 'liked' status

In my React/TypeScript app, I have implemented an Upvote component that allows users to upvote a post or remove their upvote. The icon used for the upvote is sourced from the Grommet-Icons section of the react-icons package. When a user clicks on the icon ...

Updating the image sources of a group of image tags with a predetermined list

Looking to update a series of image source references within a specific div tag. For example: <!-- language-all: lang-html --> <div id="Listofimages"> <img src="images\2page_img_3.jpg"> <img src="images\2page_img_3 ...

The file-loader in Webpack is failing to copy the files and update the URL

I am encountering an issue with webpack file loader where it is not outputting image files. This problem arises while also importing HTML files as partials in my Angular app. Below is my webpack configuration for handling images using the file-loader: [w ...