In my last two posts (jQuery and MVC: JSON and Favorite Image Icons with jQuery and MVC) I covered some basics of jQuery’s AJAX functionality to improve user experience. One of the scenarios which may not seem particularly asynchronous friendly is form submission. Fortunately, jQuery provides for asynchronous post, and in JSON format too.
The complete code to perform this is:
$('form').submit(function(e) {
e.preventDefault();
$.post($(this).attr("action"), $(this).serialize(), function(json) {
// handle response
}, "json");
});
First, get a jQuery reference to the form element and add a submit event handler:
$('form').submit(function(e) {
Next, we need to cancel the form’s default behavior by using the preventDefault function:
e.preventDefault();
Next, and this is the cool part, we call the post method in jQuery. The post method takes four arguments: url, data, callback, and type. The first three should be familiar from the previous blog posts, but the last one is new. The type parameter specifies the type of data and accepts "xml", "html", "script", "json", "jsonp", or "text". The example above is using JSON.
Rather than hard coding the url, it can be retrieved from the form element itself:
$(this).attr("action")
And rather than manually pulling form fields into the data object, as the form may change, we can call jQuery’s serialize function on the form itself:
$(this).serialize()
Finally, we can tie it all together with an MVC action. This example uses the Employee entity from the Northwind database. Since the identifier on the Employee entity is EmployeeID and not ID, id needs to be specified as an action parameter in order to retrieve the correct employee from the database.
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult Edit(int id, Employee employee)
{
// do work
return new JsonResult { Data = new { Success = true } };
}
One common scenario for this functionality is to provide asynchronous searching within a page. Even asynchronous form submits are possible with jQuery, making your arsenal that much more powerful.