Html form no refresh

How to stop refreshing the page on submit in JavaScript?

In this tutorial, we shall learn to stop form refreshing the page on submitting in JavaScript.

Let’s cover the methods to accomplish this objective.

Читайте также:  Python yield inside with

Using event.preventDefault() to stop page refresh on form submit

In this section, we will see how to use event.preventDefault() to stop page refresh on form submission. The event.preventDefault() restricts the default page refresh behavior of the form during form submission.

Users can follow the syntax below to try this method.

Syntax

The syntax defines the form.

//Get form element var form=document.getElementById("formId"); function submitForm(event) < //Preventing page refresh event.preventDefault(); >//Calling a function during form submission. form.addEventListener('submit', submitForm);

The syntax adds an event listener to the form submission event. The callback function invokes the event.preventDefault() method that prevents the page refresh.

Example

In this example, the form contains two input fields. When the user clicks the submit button, the event handler callback function starts execution. The form submission and prevention of page refresh happen immediately.

  

Program to stop form refreshing page on submit in JavaScript using event.preventDefault()

Name:

Email:

Using “return false” to stop page refresh on form submit

In this section, we will see how to use «return false» to stop page refresh on form submission. The “return false” cancels the page refresh.

Users can follow the syntax below to try this method.

Syntax

The syntax calls a JavaScript function on the form submission action. The «return false» follows the function call.

Example

In this example, two checkboxes are the form input fields. The form has the submit event callback function and the return «false” statement.

The «return false» statement removes the page refresh on form submission. The submit button goes off, and the page displays a successful form submission upon user request.

  

Program to stop form refreshing page on submit in JavaScript using return false




Using Ajax form submit to stop page refresh on form submission

In this section, we will see how to use ajax form submit to stop page refresh on form submission. The ajax form submission is a different way to submit the form without a page refresh.

Users can follow the syntax below to try this method.

Syntax

The syntax defines a form with submitting callback function that performs the form submission.

//Get the form data var data=new FormData(document.getElementById("formId")); //Create XMLHttpRequest var xhr=new XMLHttpRequest(); //Open the connection and send the data to the server xhr.open("POST", "SERVER-SCRIPT"); xhr.send(data); //Avoids default form submit return false;

The syntax reads the form element and opens up an xhr connection. Then sends the form data to the server by blocking the default form submit action.

Example

A candidate form sample with four text fields is available in this example. The form submission event function reads this form, creates an XMLHttpRequest, and starts a connection to send the data to the server.

The «return false» statement at the end of the function definition stops the default form submission, and the ajax form submission takes place.

  

Program to stop form refreshing page on submit in JavaScript using ajax form submit

Candidate Data







Using fetch API form submit to stop page refresh on the form submission

In this section, we will see how to use the fetch API form submit to stop page refresh on form submission. The fetch API form submission is another way to submit the form without a page refresh. The page rerenders after the ajax form submits.

Users can follow the syntax below to try this method.

Syntax

The syntax has a form with submit function call to perform the fetch API form submission.

//Get the form var data=new FormData(document.getElementById("formId")); //Use fetch syntax to submit the form data fetch("SERVER-SCRIPT", < method: "post", body: data >); //Stop default form submit action return false;

The syntax reads the form data and submits it using the fetch API by halting default form submission.

Example

In this example, try the select drop-down as the input field. The form has the submit function that fetches the FormData and submits it. The «return false» statement at the end of the function stops the form submit action by default. Observe that the page rerenders after the fetch API form submit.

  

Program to stop form refreshing page on submit in JavaScript using fetch form submit



This tutorial taught us four ways to stop form refreshing the page on submit. The preventDefault() and “return false” methods are for stopping page refresh on default form submit. The ajax method and fetch API method are alternative methods for form submission without page refresh.

Источник

Submitting html form without reload the page

Sometimes, when a form is submitted, you don’t want to reload the page, instead you want to execute a javascript function only. Here are ways of executing a javascript function on form submit without reload the html page. return false; is the key to prevent the from to reolad the html page.

1. When this html form is submitted, it will call the javascript function yourJsFunction(), but it won’t reload the page.

2. Use jQuery’s submit event to handle the form submit, add return false; at the end of the submit handle function to prevent the page to reload.

3. This form has no submit input, thus it won’t reload the page because the form will never get submitted, but the javascript function will be executed the button input is clicked.

Collect the input values from the form that don’t reload the page.

Referenced from stackoverflow answer
The sample html form with some basic inputs.

First Name:

Gender:
Male:
Female:

Favorite Food:
Steak:
Pizza:
Chicken:

Select a Level of Education:

JSON

The jQuery function for converting the form input values into a json object.

$.fn.serializeObject = function()< var o = <>; var a = this.serializeArray(); $.each(a, function() < if (o[this.name] !== undefined) < if (!o[this.name].push) < o[this.name] = [o[this.name]]; >o[this.name].push(this.value || ''); > else < o[this.name] = this.value || ''; >>); return o; >; $(function() < $('form').submit(function() < $('#result').text(JSON.stringify($('form').serializeObject())); return false; >); >);

Search within Codexpedia

Источник

2 Easy Ways To Submit HTML Form Without Refreshing Page

Welcome to a quick tutorial and examples on how to submit an HTML form without refreshing the page. So you have an HTML form that needs to stay on the same page after submission?

The common ways to submit an HTML form without reloading the page are:

  1. Submit the form using AJAX.
    • var data = new FormData(document.getElementById(«FORM»));
    • var xhr = new XMLHttpRequest();
    • xhr.open(«POST», «SERVER-SCRIPT»);
    • xhr.send(data);
  2. Submit the form using Fetch API.
    • var data = new FormData(document.getElementById(«FORM»));
    • fetch(«SERVER-SCRIPT», < method: "post", body: data >);

That covers the basics, but let us walk through more examples in this guide – Read on!

ⓘ I have included a zip file with all the example code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

TLDR – QUICK SLIDES

How To Submit HTML Form Without Reloading

TABLE OF CONTENTS

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

QUICK NOTES

EXAMPLE CODE DOWNLOAD

Click here to download the source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

FORM SUBMISSION WITHOUT RELOAD

All right, let us now get into the examples of how to submit forms without reloading the page.

PRELUDE) THE HTML FORM

First, this is the simple HTML form that we will be working with (for all the below examples). Nothing “special” here, just take note of the onsubmit=»return FUNCTION()» part – We will be using Javascript to process the form instead.

METHOD 1) SUBMIT FORM USING AJAX

1A) AJAX POST SUBMISSION

  
  1. Create a FormData() object to collect data from the HTML form fields.
  2. Next, the AJAX request itself. Take extra note of the xhr.onload section, this is what to do upon completion (when the server responds) – A good place to show a “successful” message or follow up with the next step. Use this.response to fetch the server response and this.status for the HTTP status code.
  3. Finally, remember to return false . This will prevent the default HTML form submission (and not reload the entire page).

1B) AJAX GET SUBMISSION

  

If you want to do a GET submission with AJAX – It is pretty much the same process. The only difference here is that the data is appended to the URL as a query string.

METHOD 2) SUBMIT FORM USING FETCH

2A) FETCH POST SUBMISSION

  

Before some of you get a panic attack on what those then and catch means, here’s a quick crash course on defining functions in Javascript:

  • You already know this one – function myfunc (a, b) < return a + b; >
  • We can also do it this way – var myfunc = function (a, b) < return a + b; >
  • We can shorten that to an “arrow function” – var myfunc = (a, b) =>
  1. The same old “get data from the HTML form”.
  2. fetch() is pretty much the “modern version” of XMLHttpRequest() , we use it to send data to the server.
    • .then((res) =>< return res.text(); >) will return the server response as plain text (string).
    • .then((txt) =>< console.log(txt); >) will output the server response in the console… Same as xhr.onload , this is a good place to show your “successful” or “failed” message.
    • .catch((err) =>< console.log(err); >is triggered if an error occurs.
  3. return false to stop the HTML form from reloading the page.

2B) FETCH GET SUBMISSION

  

Pretty much the same again. Just change to method: «get» and append the form data to the URL query string instead.

That’s all for the code, and are a few small extras that may be useful to you.

EXTRA – HOW ABOUT THE SERVER SIDE?

YOUTUBE TUTORIAL

INFOGRAPHIC CHEAT SHEET

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Источник

Оцените статью