If I have form like this:
<form action="/Car/Edit/17" id="myForm" method="post" name="myForm"> ... </form>
how to submit it without redirecting to another view by JavaScript/Jquery? I read plenty of answers from StackOverflow, but all of them redirect me to the view returned by POST function.
You can achieve that by redirecting form's
action
to an<iframe>
. It requires no JavaScript or any other type of scripts.if you're really crafty, you can tinker with
position=absolute
andz-index
value in CSS to make sure that the frame doesn't render. If it matters that much though, you might be better off using AJAX anyway.Okay, I'm not going to tell you a magical way of doing it because there isn't. If you have an action attribute set for a form element, it will redirect.
If you don't want it to redirect simply don't set any action and set
onsubmit="someFunction();"
In your
someFunction()
you do whatever you want, (with AJAX or not) and in the ending, you addreturn false;
to tell the browser not to submit the form...in order to achieve what you want, you need to use jquery ajax as below:
UPDATED: (based on the comments below)
try this one:
UPDATE 2 (the OP added this part as this was his final solution)
This worked flawlessly. I call this function from
Html.ActionLink(...)
The desired effect can also be achieved by moving the submit button outside of the form as described here:
Prevent page reload and redirect on form submit ajax/jquery
Like this:
See jQuery's
post
function.I would create a button, and set an
onClickListener
($('#button').on('click', function(){});
), and send the data in the function.Also, see the
preventDefault
function, of jQuery!Using this snippet you can submit the form and avoid redirection. Instead you can pass the success function as argument and do whatever you want.
}
And then just do :