Click here to Skip to main content
15,902,777 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
m using jquery to submit my mvc form
$("#form1").submit();
i want to use callback function for success and failure after form submission.
tell me perfect solutions.how i can use callback functions after form submission.
Posted

1 solution

You cannot, this submits the form synchronously. Which means that you are more exposed to postback and if you try to use return false or event.preventDefault() form submission is cancelled. Simple as that! That is why, you cannot get it to work even if you tried. :)

Since this is a jQuery function you are talking about, please read more about it here on .submit() on jQuery API[^]. Do not get confused with the handler in the function. That handler is just executed when this function gets called, it has nothing to do with success of fail response from servers.

To handle the success or fail events for forms (or any requests) you need to be having an asynchronous request. Ajax, for example, is a very valid candidate for this need. In ajax requests you get to handle the success or fail (error) events.

JavaScript
$.ajax({
   url: 'your-action-url',                           // Any URL
   data: $('#yourform').serialize(),                 // Serialize the form data
   success: function (data) {                        // If 200 OK
      alert('Success response: ' + data);
   },
   error: function (xhr, text, error) {              // If 40x or 50x; errors
      alert('Error: ' + error);
   }
});


This way you can manage the states of the response. In jQuery's ajax documentation[^] they are stated and explained clearly. You can read more about them there!
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900