How to submit a form or a part of a form without a page refresh using jQuery ?
In this article, we will learn how to submit a form or a part of a form without a page refresh using JQuery, & will understand its implementation through the example.
How to prevent an HTML form to submit?
Generally, when we submit a form then we should click a submit button then our page will navigate to another route as it is mentioned in the form action attribute but we can do it at the background of the webpage without navigating the web page to other routes. And this is possible by using the event.preventDefault() method which blocks the default event and does not allow it to trigger. When we click the submit button then an event is fired, so we need to prevent this event because this event is responsible to take the user to other routes. So, we have to attach an onsubmit event listener to that form, so that when the user clicks the submit button, we can get that event object and prevent that specific event to fire, by using the preventDefault method. After preventing the event using the event.preventDefault() method then we need to get the form values and make a post request to that particular routes where we want to post our values.
- Create 2 input fields, a submit button, and a span to display the result.
- Add an onsubmit listener to the form and take a callback with one single parameter.
Example: In this example, we have taken a fake post request where we need to post some information and the server will return the id as an object.
Please Login to comment...