I’m working with forms inside jQuery Dialog, and am having some issues with the data it’s posting. First load and save works fine, posts the correct data. Until I refresh the page though, every subsequent load seems to work, as in the correct data is in the form, however, when saved, the data from the first load is what is posted 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;
});
});
I believe the problem is the
…in your
postcallback, because you haven’t specified the context for the callback. If so, changing thepostto this should fix it:…because then you’re preserving the meaning of
thiswhen thesuccessfunction is called.So why would that issue cause the behavior you’re seeing? Because if you’re not removing the
formwindiv, you’re not removing theformdialogform, which means you end up with multipleforms on the page with the same ID. Although having the same ID on multiple elements is invalid and therefore subject to undefined behavior, most browsers will give you the first matching element when you ask for an element by ID — which in your case would be the earlier form with the earlier data.Edit Re your comment: Yeah, I kind of missed the
$(this).dialog('close')there. 🙂 A couple of options: One is to remember$(formwin)in a local variable and then use it in the callback, e.g.:…and don’t bother with the
contextparam (hence my using your original$.postin this update). That works because thepostsuccess handler is a closure over theformwinElementvariable (and several other things).