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

Modify the colors of names within an array of point names and their corresponding y values using Highcharts

I am trying to customize the color for each point in an array based on its name and y value. This is what I have so far: (function(H) { H.wrap(H.Series.prototype, 'getColor', function(proceed) { this.color = generateColorForString(this.na ...

Implement Conditional Enabling of Forms in JavaScript or jQuery to Support Single Form Usage

I currently have four forms labeled as form-1, form-2, form-3, and form-4, along with three buttons named Button-1, Button-2, and Button-3. Upon loading the first JSP page, it displays form elements on the screen. My query pertains to clicking on button- ...

I made a serious error by utilizing Serializable. What steps should I take to correct this mistake?

In order to maintain backward compatibility in my android app, I have incorporated Serializable objects. Unfortunately, the way I defined my classes is causing issues: Class Foo implements Serializable { private static long serialVersionUID = 92837417 ...

Customize the Focus event for a third-party page being displayed in an iframe

When an external page loads in an iframe, it automatically gains focus causing the page to scroll to that specific iframe. Is there a method to prevent this automatic focus override? ...

Is there a way to call and update an Angular controller's $scope from external sources?

function in controller: $scope.updateData = function () { Words.fetch('update', $scope.randNum) .error(function (data) { console.log('update error: ' + data.message); }) ...

How can I verify if my discord.js bot has the necessary permissions from a server or channel?

I need to verify two things: Determine if my bot has a particular SERVER permission (return true/false based on the presence of that permission) Confirm if my bot possesses a specific CHANNEL permission (return true/false depending o ...

jQuery fails to function properly when using the .live("keyup") event

Below is the code snippet: $(document).ready(function() { $("#querybox").live("keyup", function(e) { var code = (e.keyCode ? e.keyCode : e.which); if (code == 13) { $("#querybox").blur(); } else { search(document.getElementB ...

Tip Sheet: Combining Elements from an Array of Objects into a Single Array

When I invoke the function getAllUsers() { return this.http.get(this.url); } using: this.UserService.getAllUsers().subscribe(res => { console.log(res); }) The result is: [{id:1, name:'anna'}, {id:2, name:'john'}, {id:3, name ...

Localizing HTML number input values is not functioning properly

When using an HTML number field, I encountered the following error: The specified value "101,5" is not a valid number. The value must match the regular expression: -?(\d+|\d+\.\d+|\.\d+)([eE][-+]?\d+)? I am trying to co ...

Ensuring the model accurately reflects the input's value attribute in AngularJS

I am in the process of creating a set of image "radio buttons" where only one can be selected per group. However, as a newcomer to Angular, I'm facing difficulties in maintaining the value and using it as my ng-model. Additionally, I am looking for a ...

What is the most effective way to loop through HTML elements using wildcards in Puppeteer to extract innerText?

Seeking insights for educational purposes, I am in search of the reviews on this specific page . Each page contains 10 reviews, and I have a set of HTML selectors (previously used code) to extract these comments: #review_593124597 > div:nth-child(1) &g ...

Developing an npm library with ReactJs: A step-by-step guide

As a newcomer to React, I am eager to create my own npm library in ReactJS. Taking inspiration from my existing React project, the goal is to transform it into a package (or library) that can be easily integrated into other projects. This means allowing ...

What could be causing the error 'i is not defined' in my Vue.js component script when using a basic for loop?

I have a task where I need to sort an array by version and then move all elements starting with 'ipad' to the end of the list. This code snippet is extracted from a single file Vue.js component: computed: { orderedUsers: function () { ...

Obtaining the ID from a URL in node.js

As a newcomer to the world of Javascript and node.js, I am venturing into creating a REST API with URLs structured as follows: /user/{userId}/docs The goal is to extract the value of {userId}, which, for instance, in the URL /user/5/docs would be 5. Wh ...

Emphasize a passage by clicking on a different section of text

Seeking Assistance I am currently customizing this template which incorporates the MixItUp plugin. My query pertains to highlighting the "filter tab" upon clicking on the corresponding text when hovering over each image, a task I find challenging as a new ...

Is there a solution to address this login code with multiple queries in Mongoose?

**I am currently in the process of creating a login route that can accept either a username or email. However, I encountered an issue where one field is being set to undefined when the other field is available, resulting in an error. My regex is specific ...

Transferring information from AJAX to PHP script with the click of a button

Simply put, I am in the process of adding a pop-up update panel to my to-do website using an HTML button. The website already has a login-register system and uses MySQL queries to display different tables for each user. The update buttons on the website c ...

Employing getters in the toObject() method

As I delve into the code of a Node.js Express application for learning purposes, I came across the following line that sparked my curiosity regarding the inclusion of getters and virtuals. var pgmsDbObj = chnnlList[chnnlIndex] var pgmsObj = pgmsDbObj.to ...

Combining four numbers to calculate a total with the click of a button

I am currently attempting to calculate the sum of 4 entries in 4 separate text fields, and everything appears to be working correctly except that when I click the button, the sum is not being set. For example, if I enter the number 1 in each text input, th ...

Why is ng-change not functioning properly, especially in conjunction with the Select element?

HTML <select ng-model="selectedName" ng-change="retrieveSelectedClass()" ng-options="(item.name||item) group by item.groupName for item in names" class="code-helper" id="code-helperId"> <option value="">Select Option</op ...