Suppose I have a form :
<form id="myForm" method="POST" action="/something/somewhere">
<input type="text" name="textField" />
<input type="submit" name="foo" value="bar" />
</form>
the /something/somewhere
action does not return a complete html page, but just a fragment.
I would like to let the submit button do its posting job, but catch the result of this post and inject it somewhere in the DOM.
The jQuery submit
happens before the form is actually submitted. An exemple of how it could work is:
$('#myForm').posted(function(result)
{
$('#someDiv').html(result);
});
Any way to do this?
You can use the jQuery .post()
and .serialize()
method for that.
.post() Load data from the server using a HTTP POST request.
.serialize() Encode a set of form elements as a string for submission.
.preventDefault() If this method is called, the default action of the event will not be triggered. In your case the normal submit.
Html
<form id="myForm" method="POST" action="/My/MyActionMethod">
<input type="text" name="textField" />
<input type="submit"/>
</form>
<div id="someDiv"></div>
jQuery
$(function() {
$('#myForm').live('submit', function (e) {
var form = $(this);
e.preventDefault();
$.post(form.attr('action'), form.serialize(), function (result) {
$('#someDiv').html(result);
});
});
});
MVC Controller
public class MyController : Controller
{
[HttpPost]
public ActionResult MyActionMethod(FormCollection forms)
{
// do something with forms["textField"];
return Content("<b>Hello World!</b>");
}
}
If you have trouble getting it to work (thanks IE), try
event.preventDefault ? event.preventDefault() : event.returnValue = false;
While you can hack a simple example yourself using .post
and .serialize
, if you want to do anything more than trivial, I'd suggest looking into this plugin, which is (from what github and the project page says) actively community-maintained by the jQuery folks.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With