JavaScript Coder

Javascript submit a form and stay on page

beginner javascript submit form javascript submit form stay on page javascript submit form self javascript submit form without refresh javascript submit form same page

In some cases, you may want to submit the form without leaving the current page, allowing users to continue interacting with the page without interruption.

In this article, we’ll explore how to use JavaScript to submit a form and stay on the same page.

Understanding the Basics of Form Submission

Before diving into the specifics of submitting a form without leaving the page, it’s important to understand how form submission works in general.

When a user submits a form, the data entered in the form fields is sent to the server for processing. The server then generates a response, which is sent back to the user’s browser. This response can take a variety of forms, such as a new page, a message displayed on the current page, or a file download.

By default, when a user submits a form, the browser navigates to the URL specified in the form’s “action” attribute. This means that the user is taken away from the current page and redirected to a new page.

However, it is possible to prevent the default behavior of form submission using JavaScript. This allows you to submit the form and process the data on the server without leaving the current page.

A sample form

First, create an HTML form. For example:

<form id="myform">
  <div >
    <label for="myform_name">Name</label>
    <input type="text" name="name" id="myform_name" placeholder="Your Name">
  </div>
  <div >
    <label for="myform_email">Email address:</label>
    <input type="email" name="email" id="myform_email"  placeholder="Your email">
  </div>
  <div class="form-group">
    <label for="myform_message">Message</label>
    <textarea name="message" id="myform_message" rows="3"></textarea>
  </div>
  
  <button type="submit" class="btn btn-primary">Submit</button>
</form>
</div>

Submitting a Form Using JavaScript

To submit a form using JavaScript, you can attach an event listener to the form’s “submit” event. This event is triggered when the user clicks the “submit” button or presses the “enter” key while focused on a form field.

Here’s an example of how to submit a form using JavaScript:

function submitForm(e) {
  e.preventDefault();

  var myform = document.getElementById("myform");

  var formData = new FormData(myform);

  fetch("https://show.ratufa.io/json", {
    method: "POST",
    body: formData,
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error("network returns error");
      }
      return response.json();
    })
    .then((resp) => {
      let respdiv = document.createElement("pre");
      respdiv.innerHTML = JSON.stringify(resp, null, 2);
      myform.replaceWith(respdiv);
      console.log("resp from server ", resp);
    })
    .catch((error) => {
      // Handle error
      console.log("error ", error);
    });
}
var myform = document.getElementById("myform");

myform.addEventListener("submit", submitForm);

In this example, we first use the querySelector method to get a reference to the form element. We then add an event listener to the form’s “submit” event using the addEventListener method.

Inside the event listener function, we first prevent the default form submission behavior by calling the preventDefault method on the event object. This ensures that the browser does not navigate away from the current page when the form is submitted.

Next, we use the FormData API to get the form data. This creates a new FormData object that contains all the values entered in the form fields.

Finally, we use the fetch function to send the form data to the server using an AJAX request. This allows us to submit the form without leaving the page. The server’s response is handled using the then and catch methods of the Promise returned by fetch.

Staying on the Same Page After Form Submission

To stay on the same page after submitting a form, you can simply prevent the default form submission behavior using the preventDefault method, as shown in the example above.

Once the form data has been submitted to the server and processed, you can update the current page dynamically to reflect the result of the submission. This could involve displaying a success message, updating a table or list of data on.

In the example above, the code just replaces the form element with the JSON response from show.ratufa.io


fetch("https://show.ratufa.io/json", {
    method: "POST",
    body: formData,
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error("network returns error");
      }
      return response.json();
    })
    .then((resp) => {
    
      let respdiv = document.createElement("pre");
      respdiv.innerHTML = JSON.stringify(resp, null, 2);
      //replace the form node with the newly created pre element
      //You can place a thank you message here for example.
      myform.replaceWith(respdiv);
      console.log("resp from server ", resp);
    })

All Code together

See the Pen Submit form using Javascript (using fetch api) .

Try the form above. The form submits to show.ratufa.io and displays the result. You can even tweak the form above and see the results!

See Also