"Troubleshooting an Object Error When Making an Ajax Call in a Spring

Screenshot showing an ERROR I am attempting to input a value using an AJAX call through a Spring MVC controller. However, it is throwing an Object Error when the button is clicked. Can someone please assist me with this issue?

CODE: Ajax Code:

  <script type="text/javascript">
    //     $(document).ready(function() {
    function doAjaxPost() {
        //           // get the form values     
        $.ajax({
            type : "POST",
            async: "false",
//          url : "${pageContext.request.contextPath}/leadstatus_creation",
            url :'/ajax/leadstatus_creation',
            data: $('#frm-createlead-status').serialize(),
            success : function(data) {
            if(data != null && data !='')
                {
                    $('#txtleadname').val(data); 
                }               
            },  
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }
        });
    }
    //           });
</script>

LeadController.java

/**
     * Method used for View lead status get method.
     * @param map
     * @return
     * @throws Exception 
     */

@RequestMapping(value="/ajax/leadstatus_creation",method=RequestMethod.POST)
public @ResponseBody String createleadstatus(BindingResult result,HttpSession session,HttpServletRequest request,HttpServletResponse response) throws Exception{
    String resultStr=leadDao.createLeadStatus(null);        
    try 
    {   
        if(session !=null)
        {               
            String leadstatus = request.getParameter("txtleadname");
            Map<Integer,Object>obj=null;
            obj=new HashMap<Integer , Object>();
            obj.put(1, leadstatus);
            obj.put(2, 1);
            if(leadDao.createLeadStatus(obj) != null)
            {
                resultStr = "true";

            }
            else
            {
                resultStr = "false";

            }

            resultStr = JSONValue.toJSONString(resultStr);
        }
        response.setContentType("application/json");
        response.getWriter().write(resultStr.toString());           

    } catch (Exception ex) {
        System.out.println(ex.getMessage());
    }
    return resultStr;
}
}

Form Code:

Answer №1

Make sure to assign an ID to the button used for submitting data in your Spring controller.

<a id="frm-createlead-status" > POST </a>

Then, you can trigger the execution of a function when the page loads using the 'click' event.

<script type="text/javascript">

$(document).ready(function(){    
    $('#frm-createlead-status').on('click', function(event){


        $.ajax({
            url :'/ajax/leadstatus_creation',
            type: 'POST',
            data: $(#frm-createlead-status).serialize(),
            success: function(data){
                if(data != null && data !='')
                {

                  $('#txtleadname').val(data); 
                } 
            },               
            error : function(XMLHttpRequest, textStatus, errorThrown) {
                alert(textStatus);
            }

        });

    });
});

</script>

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

Adding to and retrieving data from an array

I am relatively new to the world of JavaScript and jQuery, and I have spent the last three days working on a script. Despite my efforts to find a solution by searching online, I have been unsuccessful so far. It seems like my search skills are lacking. My ...

Android Studio does not support the use of 'in'

I recently started coding in android studio and encountered an error while trying to rewrite a program. I'm unsure of how to resolve it. package com.example.music; import android.support.design.widget.TabItem; import android.support.design.widget.Ta ...

Query in JSONPath to retrieve elements in an array depending on a specified key's value

I am working with a JSON Array that contains multiple JSON objects: [ { "s3_uri":"s3://fake-s3-bucket/fact_table/fact_table.csv", "dataset":"fact_table" }, { "s3_uri":"s3://f ...

JSON returns null and the sequence of items is altered

My WCF used to only return the first and last name successfully. Recently, I made changes to include an additional piece of data which is coming up as null. The ordering has also become jumbled, with the new field appearing between the first and last nam ...

Filtering Arrays of Objects: A Guide to Filtering in JavaScript

Could really use some assistance with sorting an array of objects in javascript. My users array looks like this: var users = [ { first: 'Jon', last: 'Snow', email: '<a href="/cdn-cgi/l/email-protection" class="__ ...

Node.js version 12.7 does not have the ability to support dynamic keys within objects

According to what I've read about ecma6, it should allow for dynamic key objects. I recently upgraded my node to version 0.12.7, but I'm still encountering an error. node /var/www/games/node_modules/app.js /var/www/games/node_modules/app.js ...

Eliminating property while saving data to JSON file

I have retrieved data from an API in JSON format, saved it to a JSON file on a web server, and now I am displaying specific content from that file on a webpage using Angular.js. The NodeJS code I am using to save the API response to a file is as follows: ...

What are some ways to prevent "window.onbeforeunload" from appearing when a form is submitted?

Is there a way to prevent the alert box from appearing when submitting a form using the Submit button below? I want to avoid being prompted to "Leave this page" or "stay on this" after submitting the form. <script> window.onbeforeunload = ...

A guide on ensuring compatibility between various browser versions and Selenium driver versions

Need driver version for Google Chrome 65.0.3325.181 Looking for driver version for Google Chrome 58.0.2 (32-bit) ...

The issue arises when using IE8/9 with $.get and .html() functions, as the retrieved data

Below is a snippet of JavaScript code that I am currently working with: $(".refresh").on("click touch", function () { $.get($("a.suggest-date").attr('href') + '#suggestedDate', null, function (result) { console.log(result); ...

Create a sleek and dynamic navbar effect with Bootstrap 5 by easily hiding or showing it after scrolling

Is there a way to make the Bootstrap navbar hide after scrolling for 300px? I found a code snippet here that hides the navbar on scroll, but it hides immediately. How can I modify it to hide only after scrolling 300px? HTML: <nav class="autohide ...

The process of AJAX polling a JSON-returning URL using jQuery's $.ajax() method does not appear to provide up-to-date responses

I am currently working on a project that involves polling a specific URL for a JSON response using AJAX. The initial AJAX request alerts the server of my need for JSON content, prompting it to start building and caching the response. Subsequent AJAX reques ...

What is causing my Li elements to be unchecked in REACT?

Why is the 'checked' value not changing in my list? I'm currently working on a toDo app Here are my State Values: const [newItem, setNewItem] = useState(""); const [toDos, setToDos] = useState([]); This is my function: funct ...

Is there a way to eliminate the lag time between hovering over this element and the start of the

https://jsfiddle.net/mrvyw1m3/ I am using CSS to clip a background GIF to text and encountering an issue. To ensure the GIF starts from the beginning on hover, I added a random string to the URL which causes a delay in displaying the GIF. During this dela ...

How can I strip out HTML attributes from a String?

Looking for a solution to remove specific id attributes from an HTML string? Here's the scenario: <div id="demo_..." class="menu"> You have the HTML code as a string and want to remove all id attributes starting with demo_. The desired result ...

Utilizing HTML to call a function and fetching data from AngularJS

I've been struggling to retrieve the value after calling a function in my HTML file. Despite trying various methods after conducting research, I have not achieved success yet. Take a look at the code below: HTML: <div class="form-group"> & ...

Managing multiple updates or inserts in a MSSQL database using Sequelize

I have been tirelessly searching the online realms for a resolution over the past day but to no avail. The task at hand is performing a bulk upsert (update or insert) of a single model into a mssql database. Unfortunately, using bulkCreate with updateOnD ...

Issue with Refreshing Header Row Filter Control in Bootstrap Table

Currently in the process of developing an application that utilizes Bootstrap Table and its extension, Filter Control. One feature I've incorporated is individual search fields for each column to enhance user experience. The challenge I'm facing ...

``It seems that there is missing data in the result of the many-to-many relation

I am currently utilizing sequelize in conjunction with postgreSQL and nodejs. In my database, there are three relations: 1. User, 2. Link, 3. User_has_link (which serves as a relation table connecting users and links) with the following three columns: ...

Upon attempting to retrieve a package version, NPM responds with an error stating "bash command not found."

I recently set up my project with a package.json file that includes the nodemon package among others. When I run #npm list --depth 0 in the terminal, this is what I see: ├─┬ [email protected] However, when I try to check the version of nodemo ...