An Ajax request deletes interface components

Encountering an issue with form data submission to the server through AJAX. After passing the data, the account view-component reloads, but without the responsive UI controls. See the problem demonstrated https://i.sstatic.net/ciRhh.gif.

While the responsive controls still function when resizing the page past mobile view-width and back, the plus/minus icons disappear upon form submission, affecting the dropdown functionality on mobile devices. Here's how it appears on desktop: https://i.sstatic.net/SUgpT.png

Check out the jQuery code below for the AJAX Post and responsive layout:

AJAX Post

$('#AccountListContainer').on('submit', 'form' ,function (e) {
e.preventDefault()

var container = $("#AccountListContainer")
var dataToSend = $(this).serialize()

$.ajax({
    type: 'POST',
    url: $(this).attr('action'),
    data: dataToSend,
    context: AccountListContainer,

    success: function (data) {
        displayMessage(data.result, data.message)  
        
        //$.get("/Bank/UpdateAccountList", function (data) { container.html(data) })
        $(container).load("/Bank/UpdateAccountList")

        console.log('Ajax post success')
    },

    error: function () {
        console.log('Throw Error')
        //throw Error page?
    }
    
})
});

Responsive layout

$(document).ready(responsiveTransactionTable)

//Function for responsive table
function responsiveTransactionTable() {
    var isMobile = false
    var collapsibleHeadings = $('thead > tr').children().filter('.collapsible')

    //Toggle between desktop and mobile layout
    function toggleTableLayout() {
        var wWidth = $(window).width();

        if (wWidth >= 992) {
            console.log('You\'re in Desktop view')

            if (isMobile == true) {
                $('tr').unbind();
                $('.toggle-button').remove()
                $('.subData').remove()

                $('tr.data').removeClass('opened')
                isMobile = false
            }

        } else {
            console.log('You\'re in mobile view')
        

            if (isMobile == false) {
                $('tr.data > td:first-child').prepend('<span style="padding:5px" class="fas fa-plus toggle-button "></span>')
                isMobile = true
            }

            //Add click event for displaying hidden records in dropdown
            $('tbody > tr').unbind('click').bind('click.', function (e) {

                var selectedRow = $(this)
                var toggleIcon = selectedRow.find('.fas')

                if (selectedRow.hasClass('opened')) {

                    toggleIcon.removeClass('fa-minus').addClass('fa-plus');
                    selectedRow.next('tr').remove()
                    selectedRow.toggleClass('opened')
                } else {
                    toggleIcon.removeClass('fa-plus').addClass('fa-minus');

                    var newRow = $('<tr>').addClass('subData')
                    var cols = "";

                    cols += "<td colspan='100%'>"
                    cols += "<div style='dispaly:block'>"
                    cols += "<table class='table'>"

                    selectedRow.children().filter('.collapsible').each(function (index) {
                        cols += "<tr>"
                        cols += "<th>" + collapsibleHeadings.eq(index).text() + "</th>"
                        cols += "<td>" + $(this).text() + "</td>"
                        cols += "</tr>"
                    })

                    cols += "</table>"

                    newRow.append(cols)
                    newRow.insertAfter(selectedRow)

                    selectedRow.toggleClass('opened')
                }
            })
        }
    }

    toggleTableLayout()
    $(window).resize(toggleTableLayout)


    $('#AccountListContainer').on('show.bs.collapse', '.collapse', function () {
        $(this).prev().find('.fas').removeClass('fa-chevron-down').addClass('fa-chevron-up')

    }).on('hide.bs.collapse', '.collapse', function () {
        $(this).prev().find('.fas').removeClass('fa-chevron-up').addClass('fa-chevron-down')
    })
}

Seeking insight on resolving this issue encountered during AJAX post, where the plus/minus icons and dropdown functionality remain intact in mobile view. Any help or suggestions would be appreciated. Thank you.

Note: The error depicted in the demo GIF occurs when input == null and the records are dummy data.

Answer №1

Here is the solution I found:

I decided to utilize my ResponsiveTransactionTable() function as the second argument in jquery's .load()

$('#AccountListContainer').on('submit', 'form' ,function (e) {
e.preventDefault()

var container = $("#AccountListContainer")
var dataToSend = $(this).serialize()

$.ajax({
    type: 'POST',
    url: $(this).attr('action'),
    data: dataToSend,
    context: AccountListContainer,

    success: function (data) {
        displayMessage(data.result, data.message)  
        
        //$.get("/Bank/UpdateAccountList", function (data) { container.html(data) })
        $(container).load("/Bank/UpdateAccountList", function () {
            responsiveTransactionTable()
        })
       

        console.log('Ajax post success')
    },

    error: function () {
        console.log('Throw Error')
        //throw Error page?
    }
    
})

});

After implementing this change, here are the results:

https://i.sstatic.net/xBHjn.gif

A big thank you to @charlietfl for their helpful responses

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

Ways to include a div class in JQuery

Hey there! I'm currently working on incorporating the bootstrap panel head and body using JQuery. Here is a snippet of my HTML code: <div class="panel panel-default"> <div class="panel-heading"> <h3 class="pan ...

Creating a color icon for StackExchange using HTML

I am currently working on building my personal website. I am looking to include a link to my Stack Exchange profile on my site using the Stack Exchange icon. However, the icons available in Font Awesome are grayscale and not colored like other icons such a ...

Having trouble accessing the href attribute after clicking on an <a> tag with JavaScript

My issue lies in retrieving the href attribute of <a> tags when there is another element nested inside them: Here's the code snippet: const $elems = document.querySelectorAll('.content-container a') var elems = Array.from($elems) e ...

I'm encountering an error when trying to use makeStyles

Something seems off with MUI. I was working on my project yesterday and makeStyles was functioning properly, but now it's suddenly stopped working. I'm encountering an error when calling it here: https://i.sstatic.net/tBf1I.png I suspect the iss ...

What is the best way to ensure input text fills the entire grid?

Take a look at this code snippet: <div class="form-group col-md-6"> <label class="col-md-4">Last Updated (Real Time)</label> <input class="form-control col-md-8" type="text" ng-model="status.lastUpdated" ng-readonly="true"/ ...

Is it possible that CSS files are not being excluded from content scripts in manifest.json?

I am looking to create a chrome extension that enforces a specific CSS style on all websites except for Gmail. However, I am facing an issue where the code in the content scripts section of the manifest.json file is not working as expected. Even though I h ...

Can the Next button in the calendar be activated when the endDate Script is in use?

$('.form_date').datetimepicker({ language: 'fr', weekStart: 1, todayBtn: 0, autoclose: 1, todayHighlight: 1, startView: 2, minView: 2, forceParse: 0, // yearRange: ...

Press the button corresponding to a specific custom data-id using the console

I have a collection of items, each represented by a button with a unique data-id, for example: <button type="button" class="stuff" data-id="123"> I am looking to programmatically click on a specific button using its da ...

Is there a way I can ensure that two elements have identical heights?

Is there a way to ensure that two different elements in HTML are always the same height using CSS? I attempted to achieve this by setting each element to 50vh in the CSS, but it didn't work. codepen: https://codepen.io/ichfickedeinemutterdudummerwich ...

Color of the background in an Ionic tab

https://i.sstatic.net/lyhMu.jpg Hello, I am currently working on developing a mobile app using Ionic. I have utilized the Ionic tabs template, but I am facing an issue with the tab's background color remaining white at the bottom of the screen. Altho ...

AngularJS event that is triggered once all scopes have been applied

In my AngularJS application, I am retrieving data from a REST service. Occasionally, the brackets {{}} used to access values from scope are initially rendered and then replaced by the actual values later on. My goal is to add an ng-switch to the main DIV o ...

Discovering elements that are currently visible in an Angular list

Suppose there is a variable named users which represents an array We have the following ng-repeat statement: ng-repeat="user in users | filterUser: searchUser: assignedUsers: selectedDivision" After filtering the users using searchUser and selectedDivis ...

Issues with the functionality of customisable list items in a list

I am attempting to customize the appearance of specific list items within a ul element. One li element should be displayed in red font, while another li element should have a hyperlink styled with a different color and an underline rollover effect. The thi ...

Guide to sending DevExtreme data grids to ASP.NET MVC controllers

Currently, I am utilizing a datagrid with DevExtreme. I am wondering how I can pass the datagrid to my controller in ASP.NET MVC. In my view, I have attempted the following: @using (Html.BeginForm("action-name", "controller-name", FormMethod.Post)) { ...

Ways to enclose this text with a white border and apply a box-shadow

How can I modify text similar to this image and what is the process involved? https://i.sstatic.net/lFcGV.png ...

Using Angular parameters in Laravel blade files is a powerful tool that can enhance the

Is there a way to utilize Angular parameters in Laravel blade? I attempted the following code: <?php echo \Carbon\Carbon::createFromTimeStamp(strtotime(@{{user.lastseen}})->diffForHumans() ?> and {{\Carbon\Carbon::createFr ...

The website is missing the display of Google Maps

The Google map is not displaying on my website page that uses PHP. I need assistance with this issue. Below is the webpage URL and the source code: <section class="meteor-google-map fullwidth block" style="height: 450px; border: solid transparent; bo ...

Utilizing inline styles with the asset pipeline feature in Rails

<%= link_to root_path do %> <div class=""> <div style="background-image:<%= image_tag " image1.png "%>"> </div> <div> <h2>Title</h2> <p>Paragraph</p> </div& ...

What causes isomorphic-style-loader to generate a TypeError: Cannot read property 'apply' of undefined when utilized alongside CSS-Modules?

Currently, I am working on server-side rendering the application, and while the HTML and JS are loading fine, I have encountered an issue with my styles (.less | .scss) not being loaded. After some research, I believe that the problem lies in missing the i ...

Concerns with the Width of Gutters in Susy

I am working with a 24 Susy column grid and trying to create boxes that span 6 columns each, allowing for 4 boxes per row. However, I also want to add gutters around them within a wider container that is 24 columns wide. Despite my efforts, the columns do ...