views:

288

answers:

2

I'm trying to do some data entry via a jQuery modal Dialog. I was hoping to use something like the following to gather up my data for posting.

data = $('#myDialog').serialize();

However this results in nothing. If I reference just the containing form instead myDialog then I get all the fields on the page except those within my dialog.

What's the best way to gather up form fields within a dialog for an AJAX submission?

+1  A: 

The reason this is happening is that dialog is actually removing your elements and adding them at root level in the document body. This is done so that the dialog script can be confident in its positioning (to be sure that the data being dialog'd isn't contained, say, in a relatively positioned element). This means that your fields are in fact no longer contained in your form.

You can still get their values through accessing the individual fields by id (or anything like it), but if you want to use a handy serialize function, you're going to need to have a form within the dialog.

David Hedlund
A: 

I've just run into exactly the same problem and since I had too many fields in my dialog to reference them individually, what I did was wrap the dialog into a temporary form, serialize it and append the result to my original form's serialized data before doing the ajax call:

function getDialogData(dialogId) {
    var tempForm = document.createElement("form");
    tempForm.id = "tempForm";
    tempForm.innerHTML = $(dialogId).html();
    document.appendChild(tempForm);
    var dialogData = $("#tempForm").serialize();
    document.removeChild(tempForm);
    return dialogData;
}

function submitForm() {
    var data = $("#MyForm").serialize();
    var dialogData = getDialogData("#MyDialog");
    data += "&" + dialogData;
    $.ajax({
        url: "MyPage.aspx",
        type: "POST",
        data: data,
        dataType: "html",
        success: function(html) {
            MyCallback(html);
        }
    });
}
Veli