Jimmy
Jimmy

Reputation: 9815

replace form post method with jquery ajax method

I have a form within an ASP.NET MVC application and I'm trying to submit it via AJAX but whenever I replace my form submit with jquery like so:

$('#formID').submit(function() { });

it still does the actual post back in the form itself instead of jquery taking over, am i doing something wrong?

Upvotes: 0

Views: 997

Answers (4)

Jonas
Jonas

Reputation: 1563

You can also do something like this:

$('#formID').submit(function(e) { 
    e.preventDefault();
    /* your code */
});

With this you don't need to mix in javascript in your html and you can allow/disallow the default action just like returning false/true would.

Upvotes: 2

Just a reminder though, if you fire the submit event yourself with jQuery, the onclick won't be called and your form will be submited normally.

In general, form's onclick only fires on real user submission.

Pay attention to that while reading the two good answers John and Yuriy gave you

Happy AJAXing!

Upvotes: 0

Yuriy Faktorovich
Yuriy Faktorovich

Reputation: 68667

You need to cancel the form's submit functionality. You can do this by either having your function always return false; or prevent functionality with jquery using preventDefault().

Upvotes: 1

John Gietzen
John Gietzen

Reputation: 49534

You need to return false from the onclick event to prevent the post-back from happening. You can actuall just add an onclick property like onclick="return false".

Upvotes: 1

Related Questions