IEnumerable
IEnumerable

Reputation: 3790

Posting a form with ajax and unknown form fields

Using jQuery its quite simple to post data to a server using ajax.

Is there a jquery function to post a form using the form name and receive the status from the server like other traditional ajax post calls.

But what if we simply wanted to post a form by its name or ID and when I have an unknown set of form fields.

What Id like to do is fetch the form on the page, and just submit the form and current data

See example code:

HTML

<form name='myform'>
    <input type='hidden' value='1' name='somefield'>
    <input type='hidden' value='2' name='somefield2'>
    <input type='hidden' value='3' name='somefield3'>

</form>

<a href='#' class='postform' form_name='myform'>post using ajax</a>

JS

$('.postform').click( function() {

    form_name = $(this).attr('form_name');

    postto = 'http://mysite-endpoint.com/api';

    form = $(form_name).submit(postto).done(function(data)
    {
        var ndata = jQuery.parseJSON(data);

        if(ndata.status=='error')
        {
            //display error
        }

        if(ndata.status=='success')
        {
            //looks good
        }
    });

    return false;
});

Upvotes: 0

Views: 665

Answers (1)

Nathan Taylor
Nathan Taylor

Reputation: 24606

You can use jQuery $.serialize() to tokenize the form and submit based on the form attributes. Something like this:

$('#someform').submit(function(ev) {
    ev.preventDefault();
    var $form = $(this);

    $.ajax($form.attr('action'), {
        type: $form.attr('method') || 'get',
        data: $form.serialize(),
    }).then(function() {
        alert('success');
    }, function() {
        alert('error');
    });
});

Here's a fiddle.

Upvotes: 2

Related Questions