David
David

Reputation: 16756

How to submit a dynamically generated form to AJAX?

I have an AJAX call which dynamically generates a HTML form. This form contains a number of elements including inputs, selects, textareas, checkboxes as well as etc.

I need to write some javascript (jquery available) to get all the fields in this form and submit them to an AJAX script. I won't know how many or what fields are there (only a basic idea) as it all depends on what the user does.

Any ideas how to do this? Lets say my form name is 'ajaxform'

Upvotes: 0

Views: 9474

Answers (4)

momo
momo

Reputation: 21353

As everyone said, use jQuery serialize. One other note is to override your form submit (if needed) via jQuery live method:

    //Override form submit
    $("form").live("submit", function (event) {
        event.preventDefault();
        var form = $(this);
        $.ajax({
            url: form.attr('action'), // Get the action URL to send AJAX to
            type: "POST",
            data: form.serialize(), // get all form variables
            success: function(result){
                // ... do your AJAX post result
            }
        });
    });

Upvotes: 5

ChrisH
ChrisH

Reputation: 1281

var string_ready_to_be_posted = $('form[name="ajaxform"]').serialize(); As addon for using NAME-selector instead of ID

Upvotes: 0

Arnaud Le Blanc
Arnaud Le Blanc

Reputation: 99929

You can use jQuery's .serialize():

var data = $('#ajaxform').serialize();
var action = $('#ajaxform').attr('action');
$.post(action, data, function(data) {
 ...
});

Upvotes: 0

genesis
genesis

Reputation: 50982

var string_ready_to_be_posted = $("#formId").serialize();

http://api.jquery.com/serialize/

Upvotes: 2

Related Questions