Two POSTs When Using jQuery
I am using the jQuery UI Tabs to display a number of forms (each tab can contain more than one form). When I switch between tabs, I am attempting to do POST of the tab's forms using AJAX calls. Here is the jQuery for what I am doing.
select: function (event, ui) {
var tab_index = $('#tabs').tabs('option', 'selected');
var panel_id = $("ul li a:eq(" + tab_index + ")", this).attr("href");
var panel = $(panel_id); // the content of the tab
// For each form in the panel, submit it开发者_运维问答 via AJAX and update its HTML accordingly.
$(panel).find("form").each(function () {
var that = this;
$.post($(this).attr("action"), $(this).serialize(), function (data, success) {
if (success) {
$(that).html(data);
}
});
});
},
This works in IE and partially works in Firefox. On some of the tabs within Firefox, when I switch between tabs after a few times, two quick posts happen in succession (I can see it happen in the Console). This results in the incorrect data being posted back to the HTML (I lose error messages and the original data from the server). I can reproduce this problem every single time. Anybody have any suggestions as to what is happening here?
Update: They problem happens consistently on the same tabs. There is nothing obviously different (or no similarities exist) between the tabs that work, and those that fail. With respect to the data being POSTed when two happen quickly in a row, the first POST contains no data (AKA, I don't think serialization is happening properly) and the second POST is the correct form, but it has none of the changes that I made to the form (because the first POST reset the form).
It turned out the problem was very simple (the "biggest" bugs always are).
Basically, when I was submitting the various forms (via the individual tab forms), I had to inject the posted form back into the tab so that the user could see any updates or errors that occurred to the data after processing the POST. So, I was doing that like this (originally):
// Post a form when it has been submitted.
function postForm(form) {
$.post($(form).attr("action"), $(form).serialize(), function (data, success) {
if (success) {
$(form).html(data);
}
});
}
What I didn't know (basically due to a "reading fail") is that the .html(data) method INJECTS rather than REPLACES. As a result, I was "nesting" forms which was causing all sorts of errors in other portions of my website.
As a result, when I changed the code so it injects into the parent (like the following code), it worked perfectly, and also fixed a few other problems I was having:
// Post a form when it has been submitted.
function postForm(form) {
$.post($(form).attr("action"), $(form).serialize(), function (data, success) {
if (success) {
// Inject the resulting form back into the parent of the page.
var parent = $(form).parent();
parent.removeData($(form));
parent.html(data);
}
});
}
Reading the documentation...always a good thing...
精彩评论