convert jquery.submit to ajax submit
I can't seem to figure out how to submit a form from the jquery ui button function using Ajax.
Here's my script that submits the form via the conventional way
$('#contact-form').dialog({
modal: true,
autoOpen: false,
buttons: {
Cancel: function () {
$(this).dialog('close');
},
Ok: function () {
$('form#contactUs').submit();
$(this).dialog('destroy');
}
}
开发者_开发问答});
$('#contact-us').click(function () {
$('#contact-form').dialog('open');
return false;
});
});
and here's my form
<div id="contact-form" class="hidden" title="Online Request Form">
<form action="/Main/Contact/contactUs" method="post">
<div>
<label for="Name">Name</label><br />
<input name="Name" /><br />
<label for="PhoneNumber">Phone Number</label><br />
<input name="PhoneNumber" /><br />
<label for="EmailAddress">Email Address</label><br />
<input name="EmailAddress" /><br />
<label for="Question">Question or Comment</label><br />
<textarea name="Question"></textarea><br />
<label for="Security">What color is an orange?</label><br />
<input name="Security" />
<noscript>
<input type="submit" name="submit" value="Ok" />
</noscript>
</div>
</form>
</div>
How can I change this up to submit the link via Ajax so that I can display a success message?
This is probably sufficient:
$("#contact-form form").submit(function(e) {
e.preventDefault();
$.post( $(this).attr('action'), $(this).serialize(),
function(resp) {
if(resp == "success") {
alert('Submission was successful');
} else {
// something else
}
}
});
});
Brief explanation:
- Bind an onsubmit event handler to the contact form. Prevent the 'normal' submit.
- Serialize the form, and send the result to the form's action.
- Evaluate the response, and somehow display a message.
Further reading:
- http://docs.jquery.com/Post
- http://api.jquery.com/category/events/event-object/
- http://api.jquery.com/serialize/
Here's the solution I found
<div id="contact-form" class="hidden" title="Online Request Form">
@Using (Ajax.BeginForm("Contact", "Main",
Nothing,
New AjaxOptions With {.UpdateTargetId = "", .HttpMethod = "post"},
New With {.id = "contactUs"}))
@<div>
<label for="Name">Name</label><br />
<input name="Name" /><br />
<label for="Phone">Phone Number</label><br />
<input name="Phone" /><br />
<label for="Email">Email Address</label><br />
<input name="Email" /><br />
<label for="Question">Question or Comment</label><br />
<textarea name="Question"></textarea><br />
<label for="Security">What color is an orange?</label><br />
<input name="Security" />
<noscript>
<input type="submit" name="submit" value="Ok" />
</noscript>
</div>
End Using
</div>
<script>
$(function () {
$('#contact-form').dialog({
modal: true,
autoOpen: false,
buttons: {
Cancel: function () {
$(this).dialog('close');
},
Ok: function () {
$('form#contactUs').trigger('submit');
$(this).submit();
}
}
});
$('#contact-us').click(function () {
$('#contact-form').dialog('open');
return false;
});
});
</script>
精彩评论