Sending a string parameter from an AJAX function to a Spring controller

I'm currently developing a standalone application and facing an issue with passing a string, which is generated from the change event, to the spring controller using the provided code snippet.

Here is the HTML CODE snippet:

<!DOCTYPE HTML>
<html xmnls:th="http://www.thymeleaf.org">
<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
    <title>ADD NEW BILL</title> 
    <!-- jquery -->
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
    <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script type="text/javascript">
    $(function() {
        $("#Mandy_Name").autocomplete({
            source: "autocomplete", 
            minLength: 3        
        });
    });     
    </script>
    <script type="text/javascript">
    $(document).ready(function(){
        $("#Mandy_Name").change(function(){
            var changed =  $(this).val();   
            console.log(changed);           
            $.ajax({
                type : "POST",  
                dataType : 'json',
                url : "mandyname",
                data: {name:changed},       
                success: function(data) {
                    console.log(data);              
                    return false; 
                }   
            }); 
        });                             
    });     
    </script>
</head>
<body>
<div class="container">
<hr>
<p class="h4 mb-4">SAVE NEW PURCHASE BILL</p>
    <form action="#" th:action="@{/savePurchase}" 
        th:object="${purchase}" method="post">
        <input type="hidden" th:field="*{ID}">
        
        MANDY NAME : <input id="Mandy_Name" type="text" th:field="*{mandyName}"
                    class="form-control mb-4 col-4" placeholder="Mandy Name">   
                
        GSTIN : <input type="text" th:field="*{gstin}"
                    class="form-control mb-4 col-4" value = gst() placeholder="GSTIN">
            
                    <button type="submit" class="btn btn-info col-2">SAVE</button>
    </form>
    <br><br>
    <a th:href="@{/purchaselist}">BACK TO PURCHASE LIST</a>
</div>
</body>

</html>

The controller code is as follows:

@RequestMapping(value = "mandyName", method = RequestMethod.POST) 
 public ModelAndView getSearchResultViaAjax(@RequestBody Purchase purchase, HttpServletRequest request,
            HttpServletResponse response)
 { 
     ModelAndView mv = new ModelAndView();
     String name = purchase.getMandyName();
     System.out.println(name);
     return mv;
     
 } 


 

An error message "Failed to load resource: the server responded with a status of 404 ()" is appearing in the browser's console.

I need assistance in successfully passing the string "changed" to the controller.

Current dependencies in use:

  • jquery from "org.webjars"
  • spring-boot-starter-actuator
  • spring-boot-starter-data-jpa
  • spring-boot-starter-web
  • spring-boot-starter-data-rest
  • spring-boot-starter-thymeleaf
  • spring-boot-devtools
  • spring-boot-starter-json
  • mysql-connector-java
  • spring-boot-starter-test
  • junit-vintage-engine
  • spring-boot-maven-plugin

Are there any other necessary dependencies that should be included?

Answer №1

The HTTP Status 404 indicates that the server couldn't find the requested URL.

It seems like there is an issue with the Ajax call due to an incorrect URL being used. Make sure to update it according to your specific Spring App and port settings.

Typically, the correct URL should be: http://localhost:8080/mandyName. However, it's important to verify this information.

Here is a snippet of sample JS code:

 $(document).ready(function(){
        $("#Mandy_Name").change(function(){
            var changed =  $(this).val();   
            console.log(changed);           
            $.ajax({
                type : "POST",  
                dataType : 'json',
                url : "http://localhost:8080/mandyName", // ~~ MAKE SURE TO UPDATE THIS PART ~~
                data: {name:changed},       
                success: function(data) {
                    console.log(data);              
                    return false; 
                }   
            }); 
        });                             
    });     

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

Error: Unable to access the 'Result' property because it is undefined

I am encountering an issue while attempting to showcase database results, and the error message I'm receiving is: TypeError: Cannot read property 'Result' of undefined I am in the process of developing a Single Page Application with Angula ...

What advantages do constant variables offer when selecting DOM elements?

What is the significance of declaring variables as constant when selecting elements from the DOM? Many developers and tutorials often use const form = document.querySelector('form'); ...

What causes the discrepancy in the output values of the sha1 algorithm when using the packages object-hash and crypto/hashlib

On my frontend, I have implemented a JavaScript function that compares two sha1 hashes generated by the object-hash library. This is used to determine if there are any changes in the input data, triggering a rerun of a processing pipeline. To interact wit ...

Accordionify your jQuery with integrated YouTube and Soundcloud embedding

Right now, I am in the process of creating a page dedicated to upcoming music releases. Each release will have its own preview embedded from YouTube or Soundcloud. My goal is to organize these embeds into accordion panels with automatic start/stop function ...

How to use getServerSideProps in Next.js

In my current scenario, I find myself within a folder in the pages directory, specifically in a file named [id].jsx. My goal is to make getServerSideProps return just the name of the page, for example /page/id123 should return id123. import Link from &a ...

What is the reason behind the lack of asynchronous functionality in the mongoose find method

Outdated code utilizing promises I have some legacy code implemented with mongoose that retrieves data from the database. The schema being accessed is AccountViewPermission. Everything works fine as I am using a .then, which essentially turns it into a Pr ...

Encountering difficulties when attempting to store files using mongoose in a node express.js program

I encountered an error while attempting to save a document to the MongoDB using Mongoose in my Node Express.js project. Below is the code snippet: exports.storeJob = async (req, res, next) => { const { name, email, password, title, location, descri ...

Learn the steps for showing a kendoDropDownList using ajax in the ASP.NET MVC framework

I am currently facing an issue with my Kendo kendoDropDownList. I am trying to populate the drop down values by making an Ajax call. However, every time I click on the drop down, it calls the Action and retrieves the values, but the dropdown does not displ ...

Discover the position of a div relative to another div using ng-drag-drop

I'm currently working on a web application that allows users to create their own identity cards. For this project, I am incorporating the ng-drag-drop library from https://www.npmjs.com/package/ng-drag-drop. The main goal is to obtain the coordinate ...

Is there a way to have the user input data into a Firebase database directly from a Vue.js component?

Any assistance for a beginner like me would be greatly appreciated. I am currently working with vuejs and firebase to write data into the database from a vue component. I have successfully implemented authentication and writing functionality, but now I wan ...

Make changes to an array in Javascript without altering the original array

I currently have an array : let originalArr = ['apple', 'plum', 'berry']; Is there a way to eliminate the item "plum" from this array without altering the originalArr? One possible solution could be: let copyArr = [...origin ...

Determine the number of rows in an Excel spreadsheet using JavaScript

Currently, I am working on a codeigniter project where I need to upload an Excel file. However, before uploading the file, I want to display the number of records it contains. To achieve this, I decided to create a function within my script and then call t ...

Transmit the identification to angularjs for the genuine content to be displayed

I have a hidden field where I store an Id, which can also be 2, 3, 4, or 59. I need to send this Id from the hidden field to my opgaver.js file so it can download the content. However, I am facing difficulty in figuring out how to pass the Id to the opgav ...

Tips on building an immersive interactive panoramic website

I have a vision for a website that will simulate being in a room, where users can explore the space with limited panoramic views - allowing them to look up/down 30 degrees and left/right 45 degrees. In addition, I would like to integrate interactive object ...

Emphasize specific letters in a word by making them bold, according to the user

In my app, there is a search feature that filters data based on user input and displays a list of matching results. I am trying to make the text that was searched by the user appear bold in the filtered data. For example, if the user searches 'Jo&apos ...

Removing data with sweetalert in a Ruby on Rails application

Hey there, I'm currently exploring the use of sweet alert js to enhance the appearance of my alert boxes. In my table, I have a specific data deletion feature that is triggered by a standard JavaScript alert confirmation. However, when attempting to i ...

What methods can Ajax utilize to make asynchronous requests and receive synchronous responses?

While using jQuery ajax to send a request to a web service, I came across an interesting bug: var AjaxResult; login = function () { AjaxResult = ""; $.ajax({ type: "POST", url: KnutBase.getServiceUrl() + "ServiceInterface/HmsPlanne ...

What is the best way to create a scrollable Material UI modal and dialog?

Having a problem with my mui modal where the top content is getting cut off and I can't scroll up. I've tried adding the {overflow:"scroll"} property to the modal but it's not working. Here's the code snippet I'm currentl ...

Can anyone suggest a method for adding comments and improving the organization of a bower.json file?

Managing a large project with numerous bower dependencies can be challenging. It's often unclear whether these dependencies are still being used or if the specified versions are necessary for a reason. It would be ideal to have the ability to add comm ...

Adding new controls dynamically in an ASP.NET UpdatePanel with AJAX may require line breaks to be properly displayed

I seem to be struggling with a basic concept here and I'm not sure how to proceed. Below is the code from my Default.aspx file: <asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent"> <asp:ScriptManager ID="Main ...