Attempting to utilize the Put method with Ajax, but the script does not seem to be executing

Currently, I am working on implementing the Put method using Ajax:

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $('#submitPut').click(  function () {
                console.log("click");
                var sendName = $('#name').val();
                var sendDescription = $('#description').val();

                $.ajax({
                    url: '/musicalstyle',    
                    type: 'PUT',   
                    data: {
                        name: sendName,
                        description: sendDescription,

                    },      
                    success: function () {
                    }
                })
                ;

            });
        });
    </script>
</head>
<body>
    <form> 
        <label for="name">Nombre</label>
        <input type="text" id="name"  />
        <label for="description">Descripción</label>
        <input type="text" name="description" id="description"/>
        <input id="submitPut" type="button"  value="SubmitPut">

    </form>
</body>
</html>

While this form is functioning properly, when deployed in a real environment utilizing Thymeleaf and Bootstrap, the script fails to execute. It appears that

<button class="btn btn-primary" id="submitPut" type="button">Actualizar</button>
does not trigger the submitPut function.

The production version of the form is as follows:

    <form>
        <div class="form-group row">
            <label for="name" class="col-sm-2 col-form-label">Nombre</label>
            <div class="col-sm-6">
                <input type="text" class="form-control" id="name">
            </div>
         </div>
         <div class="form-group row">
            <label for="description" class="col-sm-2 col-form-label">Descripción</label>
            <div class="col-sm-6">
                <input type="text" class="form-control" id="description">
            </div>
          </div>
          <br>
         <button class="btn btn-primary" id="submitPut" type="button">Actualizar</button>
    </form>

If you have any insights on how to ensure the button triggers the ajax function successfully, it would be greatly appreciated!

Thank you,

Answer №1

The identifier for your input has been set to submit but you have invoked the onclick function using submitPut. Therefore,

<input id="submitPut" type="button"  value="SubmitDelete"/>

Answer №2

Hey @Biplove, just made some changes to my previous comment. Now the ID of the input matches the name of the onclick function.

Answer №3

Once I have imported JQuery using the lines of code below,

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>window.jQuery || document.write('<script src="../js/jquery.slim.min.js">
<\/script>')</script><script src="../js/bootstrap.bundle.js"></script></body>
, Ajax starts its execution.

The issue arises when my Put method in the Controller attempts to redirect to another view, although it appears to be executing correctly. The logs from Spring show:

2020-05-21 16:04:15.367 DEBUG 552 --- [nio-8182-exec-9] o.s.web.servlet.DispatcherServlet        : PUT "/musicalstyle", parameters={masked}
2020-05-21 16:04:15.368 DEBUG 552 --- [nio-8182-exec-9] s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to com.musicnet.springboot.controller.SystemAdministratorController#updateStyle(Style, Model)
2020-05-21 16:04:15.558 DEBUG 552 --- [nio-8182-exec-9] o.s.w.s.v.ContentNegotiatingViewResolver : Selected '*/*' given [*/*]
2020-05-21 16:04:15.632 DEBUG 552 --- [nio-8182-exec-9] o.s.web.servlet.DispatcherServlet        : Completed 200 OK

While the style is successfully updated through the put method, the view fails to display on the browser. Upon investigation, it seems that Spring isn't the root cause of the issue with the redirection of the view; rather, it appears that the ajax script is failing to redirect to the received view.

I am seeking guidance on how to adjust the ajax script to handle and process the returned view from Spring.

Edit

By including the following redirection command within the ajax script, I was able to achieve successful redirection:

success: function () {
            window.location.reload();
     }

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

Adapt Non-Adjacent Content Sections For XL Screens in Sidebar Without Replicating Source Code Segments

I'm struggling to figure out how to achieve my desired layout. Details The solution presented by sheriffderek using CSS grid seems promising, but it causes issues with white space when adding content to the profile block on XL screens. Adjusting the ...

How can a non-commonJS library be effectively integrated into the Webpack environment?

Looking to incorporate an external and non-commonJS library to define an AngularJS module. What is the best approach since directly importing it won't work, like this: import MyLibrary from 'MyLibraryPath' angular.module('MyApp' ...

What are some ways to optimize the performance of this MySQL query for faster execution?

SELECT * FROM (`collection_series`) JOIN `datadatexnumericy` ON `collection_series`.`series_id` = `datadatexnumericy`.`series_id` JOIN `saved_users_chart` ON `collection_series`.`collection_id` = `saved_users_chart`.`chart_id` WHERE `saved ...

Node.JS: Combining Multiple Files into a Single Output File

Currently, I am in the process of building a data pipeline using Node.js. While I acknowledge that there are better ways to approach this, I am determined to implement it and make improvements as I go. Here's the scenario: I have a collection of gzi ...

What is the best way to transfer data from a parent component to a child component in ReactJs?

When dealing with nested react elements, how can you pass values from the parent element to a child element that is not directly inside the parent element? React.render( <MainLayout> <IndexDashboard /> </MainLayout>, document.b ...

Using React Native, you can easily apply styles to View components by passing them

Is it a bug? Or is the View styles props object supporting inline props as well? For example, in the traditional way and also written in React Native documentation: function App() { return ( <View style={styles.box}></View> ) } const ...

"Obtaining Data from Local Storage on a Different Page: A Step-by-

``How can I transfer JSON data stored in local storage from one page to another within the same domain? In MainPage.html, the "user" data is stored in local storage and displayed. However, when data is added in AddEmploye.html and then returning to MainPa ...

Can REST calls be initiated when the CSP is unable to be modified from the default-src: 'none'?

Sometimes, I wonder if this question is silly because it goes against the purpose of the Content Security Policy. There's a webpage located at foo.baz.com that requires data from bar.baz.com to function locally. Below is the code snippet for the func ...

I need RxJs to return individual elements to the subscriber instead of an array when using http.get

I've been developing an Angular 2 app (RC5) with a NodeJS backend RESTful API integration. One specific route on the backend returns an array of 'Candidates': exports.list = function (req, res, next) { const sort = req.query.sort || null ...

What could be causing the jQuery change function to stop working after loading HTML with AJAX?

When loading a form, I use AJAX to dynamically populate a select element from a PHP file. Previously, my change function was working fine (it displayed another input when 'other' was selected). However, after implementing the dynamic AJAX populat ...

Guide to handling HTTP request parsing in Express/NodeJs when the content type is missing, by setting a default content type

Is it possible to retrieve POST data in an express request when the bodyParser does not work? var server = express(); server.use(express.bodyParser()); server.post('/api/v1', function(req, resp) { var body = req.body; //if request header doe ...

issue encountered while adding a new element to an array using javascript

I am encountering an issue with adding comments from HTML form elements to an array in AngularJS. Whenever I try to use the Javascript push function, I receive an error stating "property of object doesn't exist". Can someone assist me in resolving thi ...

What could be causing the issue with the malfunctioning Ajax pagination?

I attempted to incorporate ajax-loaded pagination into my project. I successfully followed a tutorial for implementing it in a blank project, but when trying to apply it to my current project, I encountered issues. Although I can navigate through the pagin ...

Experiencing a NetworkError while trying to access OWIN WebAPI 2 using jQuery

Can someone please assist me with why I am encountering a NetworkError when attempting to use jQuery Ajax to invoke a WebAPI? The Web Method is being called successfully, but an error is occurring after it returns. When I change the access to HttpGet, I a ...

The visual representation is not being generated (three.js)

I recently designed a basic scene in three.js, however I am facing an issue where it does not seem to work with the canvas renderer, even though it should work correctly. Here is the code: http://jsfiddle.net/PRkcJ/ The scene only functions properly when ...

What is the most effective way to send a large string via an ajax call to a controller in MVC

What is the best way to send a large string data (stringified data) through an ajax call to a controller in MVC? In my current situation, the size of the string is 820 KB. When the string reaches the controller, it appears as [{"Id":"2vwf35f!@#qad", .... ...

Mastering React hooks: A guide to effectively updating and rendering elements

Each time I click the delete button, it seems to only remove the last element instead of the specific one based on index. Is there a better way to achieve this without changing from <input defaultValue={name} /> to <input value={name} /> in t ...

Tips for swapping out text with a hyperlink using JavaScript

I need to create hyperlinks for certain words in my posts. I found a code snippet that does this: document.body.innerHTML = document.body.innerHTML.replace('Ronaldo', '<a href="www.ronaldo.com">Ronaldo</a>'); Whil ...

Forget the function once it has been clicked

I'm looking for a solution to my resizing function issue. When I press a button, the function opens two columns outside of the window, but I want to reset this function when I click on another div. Is there a way to remove or clear the function from m ...

Combining Mongoose OR conditions with ObjectIDs

After querying my Team schema, I am receiving an array of ids which I have confirmed is correct. The issue seems to lie in the fact that both home_team and away_team are ObjectIDs for the Team Schema within my OR statement. Team.find({ 'conferenc ...