Enhance a collection of data with Rails and Ajax

Imagine we have multiple lists of items.

<ul data-id="2">
    <li>
        <span>Item name</span>
    </li>
    <li>
        <span>Item name</span>
    </li>
    <li>
        <span>Item name</span>
    </li>
</ul>

Each item is assigned a list_id attribute, which represents the ID of the list it belongs to, and an order attribute, indicating its position in the list.

When a specific event occurs, the goal is to update the list_id and order parameters for each item in this list.

This is what has been developed so far:

$('li').sortable({
    update: function( event, ui ) {
        if (this === ui.item.parent()[0]) {

            var cards = ui.item.parent('ul li').map(function() {
                return {
                    list_id: $(this).closest('ul').data('id'),
                    order: $(this).index(),
                }
            }).get();

            $.ajax({
                url: "/cards/",
                type: "PATCH",
                dataType: "json",
                data: { cards: cards },
                success: function(resp){
                    console.log('Yay');
                }
            });
        }
    }
});

An issue arises when attempting to output the cards array. The console.log(cards); command returns an empty array [] without any understandable data. Additionally, the Rails console does not seem to show any params array either.

The objective remains to send all the cards in the list to the Rails controller and update them simultaneously.

Answer №1

One may question the choice of using the li tag for sorting, rather than the ul tag.

The purpose is to enable a group of DOM elements to be sortable.

In this scenario, it would actually be more suitable to utilize the ul tag instead of the li tag.

$('ul').sortable({
    update: function( event, ui ) {
        var list_id = $(this).data('id');
        var cards = $.map($(this).find('li'), function(el) {
            return { list_id: list_id,
                      order: $(el).index() };
        });
        $.ajax({
            url: "/cards/",
            type: "PATCH",
            dataType: "json",
            data: { cards: cards },
            success: function(resp){
                console.log('Yay');
            }
        });
    }
});
ul {
  list-style-type: none;
    margin: 0;
    padding: 0;
    width: 60%;
}
li {
    margin: 0 3px 3px 3px;
    padding: 0.4em;
    padding-left: 1.5em;
    font-size: 1.4em;
    height: 18px;
    border: 1px solid #c5c5c5;
    background: #f6f6f6;
    font-weight: normal;
    color: #454545;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<ul data-id="2">
    <li>
        <span>Item name</span>
    </li>
    <li>
        <span>Item name 2</span>
    </li>
    <li>
        <span>Item name 3</span>
    </li>
</ul>

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

Implementing auto-complete functionality using two keys in Material UI and React

My goal is to enable autocomplete for input when searching with values like title and year. Strangely, the autocomplete feature only works when I search with title. Searching with year does not yield any options. Sample code export default function ComboB ...

AngularJS: engaging search experience

I'm just starting to learn AngularJS, and I have a project where I need to create an interactive search feature. So far, this is what I have: article/views/articles.html <form class="form-inline"> <div class="form-group"> < ...

"Unexpected discrepancy: Bootstrap Glyphicon fails to appear on webpage, however, is visible

I am having some trouble getting the glyphicon to display properly in my side nav. The arrow head should rotate down, which is a pretty standard feature. Here is the link to the page: The glyphicon should be visible on the "Nicky's Folders" top leve ...

Different Approach to Angular Bidirectional Data Binding

I have been utilizing the Two Way Data Binding functionality provided by angular.js, however, this is the sole feature I have incorporated. For instance: My inquiry is: Is there an alternative platform that offers a simple setup comparable to Angular, f ...

Cordova - Fixed elements flicker/blink when scrolling

I have exhausted all possible solutions, ranging from -webkit-transform: translate3d(0,0,0); to -webkit-backface-visibility:hidden but none of them seem to resolve the issue of an element flickering/blinking/disappearing when scrolling on iOS with - ...

How can I ensure that a group of jQuery sliders are always locked to a combined total of 100?

Seeking assistance with implementing NoUiSlider on multiple pages with varying numbers of sliders (). Attempting to set up the sliders with a total value constraint of 100, enabling adjustment of one slider to affect the values of others inversely, yet un ...

What is the most efficient way to extract dynamically generated JavaScript content from a webpage?

Currently, my method involves using selenium alongside PhantomJS to scrape dynamic content generated by JavaScript on a website. Although it provides me with the desired results, the process is quite slow as I have to wait for the entire page to load befor ...

Sequentially run jQuery functions

function functionOne() { $('#search-city-form').trigger('click'); } function functionTwo() { $("form input[name='tariffId']").val("137"); $('#search-city-form').trigger('click'); } function funct ...

Is there a way in jQuery to identify if a paragraph contains exactly one hyperlink and no other content?

I need to assign the 'solo' class to a link within a paragraph only if that link is the sole element in the paragraph. This example would have the 'solo' class: <p><a>I am alone</a></p> However, this example w ...

Can you explain the functionality of the JavaScript code in the index.html file within webpack's react-scripts?

I have been experimenting with dynamically loading a React component into another application that is also a simple React app. However, I am facing challenges getting the index.js file to run properly. While referencing this article for guidance, I notice ...

The system was unable to load the gRPC binary module due to its absence in the current installation

I recently developed an electron app that utilizes Firebase's real-time database. I followed a tutorial on YouTube and carefully reviewed the documentation on Firebase's website to ensure everything was set up correctly. Here is a snippet of my c ...

Mastering the Art of jQuery Post with Iteration and Result Utilization

I am facing an issue with my code function fetchInfoFromDB() { let body = ""; let text = ""; $("tr").each(function (index) { let code = $(this).children("td:nth-child(2)"); $.post("http://urltogetdatafromdatabase.com/getinfo.ph ...

Tips for consolidating JavaScript assets in Mean.io

Recently, I started using Mean.io and encountered an issue while trying to include an external .js file in my package. Unfortunately, I seem to be doing it incorrectly as the file is not being added to aggregated.js. This is the approach I have taken: im ...

Leveraging the combination of <Form>, jQuery, Sequelize, and SQL for authentication and navigation tasks

My objective is to extract the values from the IDs #username-l and #pwd-l in an HTML form upon the user clicking the submit button. I aim to compare these values with those stored in a SQL database, and if they match exactly, redirect the user to a specifi ...

The term 'EmployeeContext' is being utilized as a namespace in this scenario, although it actually pertains to a type.ts(2702)

<EmployeeContext.Provider> value={addEmployee, DefaultData, sortedEmployees, deleteEmployee, updateEmployee} {props.children}; </EmployeeContext.Provider> I am currently facing an issue mentioned in the title. Could anyone lend a hand? ...

Using NextJS to pass a parameter to an onClick function

I've been using the react-simple-star-rating package in this sample code. However, I'm facing an issue: Within my trains parameter, there is a variable id that I would like to pass to the handleRating function using onClick, but I can't see ...

Sending formdata containing a file and variables via $.ajax

I've been working on a jquery file upload project based on a tutorial I found here: . The tutorial is great and the functionality works perfectly. However, I'm looking to add more control and security measures for user image uploads, such as inco ...

Troubleshooting: Why isn't my ASP.NET Razor Pages WebMatrix AJAX post functioning properly?

Seeking assistance with posting data to a page using ajax, but encountering issues. Any suggestions? $.ajax({ url: '/REST/GetResponse.cshtml', type: "POST", dataType: "json", contentType: "application/json; charset=utf-8", d ...

Tips for making Slider display the next or previous slide when span is clicked

I have implemented a mix of bootstrap 3 and manual coding for my project. While the image thumbnails function correctly when clicked, the span arrows do not navigate to the next or previous images as intended. Below is the code snippet: var maximages ...

Obtaining outcomes from all redux-saga operations, regardless of any potential failures

I am currently facing a situation where I have to execute multiple api calls simultaneously. The current code utilizes redux-saga's all method for this purpose: try { const results = yield all( someIds.map(id => call(axios.delete, ...