Quickly submit HTML Form in AJAX as JSON

//
//JQuery part-
//
function form_to_json(selector) {
    var ary = $(selector).serializeArray();
    var obj = {};
    for (var a = 0; a < ary.length; a++) obj[ary[a].name] = ary[a].value;
    return obj;
}

$('#SubmitTheForm').click(function (e) {
    e.preventDefault();
    var $button = $(this);
    var url = $('#form').attr("action");
    var formdata = form_to_json('#form');
    $.ajax({
        type: 'POST',
        url: url,
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify(formdata), 
        dataType: 'json',
        beforeSend: function () {
            $button.attr('disabled', 'disabled');
            $button.html('Working…');
        },
        success: function (result) {
            console.log(result);
        },
        error: function (request, status, error) {
            alert('Failed to save. Error Details – Request: ' + request + ', Status: ' + status + ', Error: ' + error);
        },
        complete: function () {
            $button.removeAttr('disabled');
            $button.html('Submit');
        }
    });
});
//
//JQuery part-
//
public ActionResult AddBr(int Id, string Name)
{
    return Json(BrName);
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s