Reputation: 882
I have a mvc3 Ajax.BeginForm. Instead of clicking on the button I would like to have the button clicked by JavaScript from a onblur event from one of the text boxes.
I've tried the code below and also just calling a function with $('#submitEmail').click(); in it. The submit works and I get a post back but the problem is in the Controller Request.IsAjaxRequest() is false. When I click the button myself Request.IsAjaxRequest() is true.
@Html.TextBoxFor(model => model.LeadEmail, new { onBlur = "this.form.submit();" })
Yes I've checked with fiddler X-Requested-With is not present when using JavaScript trigger. How can I get it to submit the form on the onBlur event and get the proper ajax header?
Upvotes: 0
Views: 682
Reputation: 26940
I want to add something to Tigran's answer:
<script type="text/javascript">
function FormAjaxSubmit() {
var f = $("form").serialize();
$.ajax({
url: "/Control/Action",
type: "POST",
data: { formCollection: f },
success: function (result) {
$('#resultDiv').html(result);
}
});
}
</script>
Upvotes: 1
Reputation: 13934
Calling submit method on a form is essentially same as clicking on submit button of a form, and when you do that, the browser does a request based on a method type (GET/POST) defined in method attribute.
Calling submit is not an ajax request, it's a form submit that does a full page reload and that is why it didn't work.
Upvotes: 0
Reputation: 882
So I'm not sure why the way I was trying doesn't work. The way I see it should work. I press the button or the code presses the button should be the same. Apparently there's a difference. Maybe somebody with knowledge in this area can inform us. But the solution is to actually do an ajax post.
<script type="text/javascript">
function FormAjaxSubmit() {
var someThing = $("#SomeThing").val();
$.ajax({
url: "/Control/Action",
type: "POST",
data: { SomeThing: someThing },
success: function (result) {
$('#resultDiv').html(result);
}
});
}
</script>
Upvotes: 1