Posting a HTML form with AJAX

Sometimes it is necessary to post the data from a HTML form not by using a submit request (e.g. through a submit button or a (JQuery) submit call) but by using an asynchronous request. This may come handy for example for single-page applications, or if a download is triggered by submitting the data. In the latter case, you might want to display a small dialog box telling the user that the data is being prepared for download. Hint: Handy for this job is a JQuery plugin by John Culviner.

Suppose you have a MVC controller in the backend, which expects a certain data model coming with the submit/POST request. Somehow you need to prepare the form data such that you can post it to the controller in the appropriate format. Usually, this is done automatically by the browser when you press the submit button. If we want to do the POST from JavaScript, we need to wrap the data ourselves. Fortunately, this is not so hard. We just need to build an object out of the form elements that hold user input data. A simple solution would be (using JQuery, and it is TypeScript, by the way, but the JavaScript version almost looks the same):

var form2object = (formName: string): any => {
var data = {};
var allChildren = $(document.getElementById(formName)).find("input, select");
for (var i = 0; i < allChildren.length; i++) {
var child = allChildren[i];
var c_name = $(child).attr("name");
var c_val = $(child).val();
data[c_name] = c_val;
return data;

As you can see, we select all children of the form that are either input or select elements. For each of these, we add a new property to a dynamic data object where the name attribute is being used as the property name. This is compatible with the way ASP.NET MVC does the model binding. The value of the property becomes the the value of the form element. This data object can then be used in a JQuery $.ajax(... call, for example.

This entry was posted in ASP.NET MVC, JavaScript, Software. Bookmark the permalink.

Leave a Reply

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

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

Google photo

You are commenting using your Google 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 )

Connecting to %s