MVC jQuery submit form (without page refresh) from JavaScript function
This is how I do that with jquery:
function DoAjaxPostAndMore(btnClicked){ var $form = $(btnClicked).parents('form'); $.ajax({ type: "POST", url: $form.attr('action'), data: $form.serialize(), error: function(xhr, status, error) { //do something about the error }, success: function(response) { //do something with response LoadBooks(); } }); return false;// if it's a link to prevent post}
I assumed that btnClicked is inside of the form:
<input type="button" value="Submit" onclick="DoAjaxPostAndMore(this)"/>
if link:
<a href="/url/something" onclick="return DoAjaxPostAndMore(this)">linktext</a>
If link is not inside for the form you just have to use jquery selectors to find it. You may set id to the form and then find form like this:
var $form = $("#theformid");
Is that Ajax.BeginForm
that you need to use, not Html.BeginForm
?
Does your "onclick" JavaScript function execute and the problem is that full page submit/refresh happens as well? In this case the problem is that you don't end your JavaScript function with return false
.
Or is the problem that your "onclick" JavaScript function isn't called at all? Then it's hard to say without looking at the code... If you use JQuery selector - then probably the link isn't picked by the selector