The issue of jQuery Dialog form serialization causing incorrect data to be reposted in future interactions

Currently, I am facing some challenges with the data being posted when working with forms inside jQuery Dialog. The initial load and save of the data work correctly. However, after refreshing the page, subsequent loads display the correct data in the form but end up posting the data from the first load every time.

function formdialog(url, tack, divid, scriptload){
    $.getJSON(url+tack+"/form", function(data){
        var formwin = '<div><form id="formdialog">'+data['form']+'</form></div>';
        var dialog = $(formwin).dialog({
            title: data['title'],
            autoOpen: false,
            modal: true,
            buttons: {
                "Save": function(){    
                    $.post(url+tack+"/process", 
                        $("#formdialog").serialize(),
                        function(data){
                            alert($("#formdialog").serialize());
                            $(this).dialog('close');
                            $(this).remove();
                        }
                    );
                },
                "Cancel": function(){$(this).dialog('close'); $(this).remove();}
            }
        });

        dialog.dialog("open");
    });
}

$(function(){        
    $("a.edlnk").click(function(){
        var url = $(this).attr("href");
        formdialog(CONFIG_HREF_SITE+"ajax/"+appControl, "/"+url, divid);
        return false;
    });
});

Answer №1

It seems like the issue lies within

$(this).dialog('close');
$(this).remove();

...in your post callback because there is no specified context for the callback function. To resolve this, you can modify the post to include the following:

$.ajax({
    url:        url+tack+"/process",
    type:       'POST',
    data:       $("#formdialog").serialize(),
    context:    this,
    success:    function(data){
        alert($("#formdialog").serialize());
        $(this).dialog('close');
        $(this).remove();
    }
});

By doing so, you maintain the reference to this when the success function is executed.

The behavior you are experiencing is likely occurring because if you do not remove the formwin div, the formdialog form will still be present, resulting in multiple form elements on the page with the same ID. Although having duplicate IDs is invalid and may lead to undefined behavior, most browsers will retrieve the first matching element when an element is requested by ID — in this case, it would be the initial form with the original data.


Edit Regarding your comment: It appears I overlooked the $(this).dialog('close'). Here are a couple of solutions: one option is to store $(formwin) in a local variable and use it within the callback, as shown below:

var formwin = '<div><form id="formdialog">'+data['form']+'</form></div>';
var formwinElement = $(formwin);     // <== Store it here
var dialog = formwinElement.dialog({ // <== Utilize it here

// ...

                $.post(url+tack+"/process", 
                    $("#formdialog").serialize(),
                    function(data){
                        alert($("#formdialog").serialize());
                        $(this).dialog('close');
                        formWinElement.remove(); // <== Also here
                    }
                );

...and eliminate the need for the context parameter (thus reverting to your original $.post method in this update). This approach works because the post success handler encapsulates the formwinElement variable (along with other variables).

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

Interacting with APIs using jQuery, managing responses with AJAX, handling parsererror in our development environment XAMPP on Windows 8

I've come across numerous questions regarding the dreaded "parsererror" but I just can't seem to find a solution that fits my specific issue. Here's the code causing me grief: <!DOCTYPE html> <html> <head> <meta http-eq ...

Error message in Prestashop console: "jsonData is null, causing a TypeError"

I'm new to Prestashop and running into an issue. Whenever someone clicks the "Add to cart" button, the console displays an error message saying "TypeError: jsonData is null" and the product doesn't seem to get added to the cart. However, upon ref ...

Why is the lifecycle callback not being triggered?

I am currently learning how to develop with Vue.js. I have been trying to use the lifecycle callbacks in my code. In my App.vue file, I have implemented the onMounted callback. However, when I run the code, I do not see the message appearing in the consol ...

When the Reload button is pressed, are ajax requests initiated by the page cached invalidated?

What occurs when the reload button on a browser is pressed and there are cached ajax calls executed at jQuery document ready? Will you receive a cached version, or will the cache be invalidated due to the Reload button being pressed? Additionally, does the ...

Limiting the invocation of the listener method in f:ajax depending on the return value of onevent

I am looking to check if the Onevent javascript function returns true or false. My goal is to restrict the listener method call based on the return value of the Javascript function. However, the code snippet provided is causing a syntax error in Firebug. ...

I need some help with adjusting the number of rows shown per page in MaterialReactTable

I've been utilizing MaterialReactTable and my goal is to display only 5 items on each pagination page. Despite setting muiTablePaginationProps, I still see 10 items per page. How can I resolve this issue? <MaterialReactTable columns={columns} ...

Backbone sorting is specifically designed for organizing views within the framework

As I work on creating a sorting function in backbone, I have come across recommendations to use views to listen for changes in collections and then render the views once the collections are sorted. However, this approach does not suit my needs for two main ...

What is the best way to integrate bootstrap modal forms using django-crispy-forms without causing a page refresh?

Recently, I've been working on setting up a form within a bootstrap modal using django-crispy forms and class-based views. While looking into incorporating Ajax functionality, I found several examples that weren't entirely clear to me. I tested ...

Ways to successfully transfer an array containing numerous mesh entities

One task I need to accomplish is parsing an array that was created in a web worker back to the main thread. This particular array contains a large number of THREE.Mesh objects. However, when attempting to stringify this array using the following code: sel ...

Unable to properly configure socket.io

(I'm new to programming, only started about a week ago) Recently, I have been working on creating a multiplayer snake game using node.js and socket.io. My goal was to implement it on my custom domain (). However, I encountered a persistent console er ...

Displaying a loading screen while a jQuery ajax request is in progress

Currently, I am attempting to display a loading div while waiting for an ajax call to finish. Despite experimenting with various methods, I have not been able to consistently achieve the desired outcome. In my present code, everything functions properly o ...

Make changes to a user within a JSON storage file by utilizing XMLHttpRequest

I am facing an issue and seeking assistance from this community to resolve it. I am attempting to modify a user in my JSON-file by creating an HTML button with the ID "editBtn". User data is stored in the file storage.JSON, and the currently logged-in user ...

"Utilizing Vue.js to make an AJAX request and trigger another method within a

How can I include another method within a jQuery ajax call? methods : { calert(type,msg="",error=""){ console.log("call me"); }, getData(){ $.ajax({ type: "GET", success: function(data){ / ...

Is this the correct method for linking the function to every individual element?

Is it correct to attach the function to each element individually? Also, is my function correctly implemented? <ul id='forShopping'> <li><input class='ch' type='checkbox' onclick='isAct ...

How can I display two slides at once in Ionic 2/3 on a wide screen?

I have been searching for a solution that will allow me to display 1 ion-slide if the device screen is small, but if it's larger, then I want to display 2 ion-slides. Unfortunately, I have not been able to find a suitable solution yet. As an example, ...

Languages that are suggested for sending emails

After extensively researching online, I have yet to find a definitive answer to my query. I am in the process of creating an HTML5 (+CSS3 +JavaScript) mobile application that needs to be able to send values from text boxes or retrieve them from a websql da ...

Encountering ENOENT error when accessing view file in NodeJS and Express

I've encountered a strange issue with my nodeJS application after refactoring it. The app launches without any problems, the API responds correctly. However, when I attempt to access "/", I receive the following error: Error: ENOENT, stat '/view ...

What is the best way to dynamically update form fields in a database after making a selection in a <select> component?

Currently, I have a form that displays a list of stars (stellar objects) with a <select> control and two <inputs>. I am seeking guidance on how to populate the two inputs from the database when the user changes the selection in the <select&g ...

Received extra keys from getStaticPaths in NextJs

Currently engrossed in a project for a client using NextJs, The blog section comprises various paths like blog/[:category], blog/[:category]/[:post], and blog/author/[:author]. To achieve this, I am utilizing getStaticPaths and getStaticProps. My approach ...

Tips for preventing automatic login when a new user is added in firebase

I am looking to enable users to create additional accounts, however, I encountered an issue when using createUserWithEmailAndPassword which automatically signs in the new user. How can I prevent this from happening? My goal is to set up a user account fro ...