HTML.form.guide

How to call javascript function from form action attribute

form action javascript form javascript form action function

HTML forms are an essential element of web pages that enable users to enter and send data. Upon clicking the submit button, the information is transmitted to the server via an HTTP request. The form’s action attribute specifies the URL where the data should be delivered.

While creating web applications, it’s common to have forms that enable users to enter and submit data. However, sometimes you may need to perform some actions on the client-side before submitting the form data to the server. This is where JavaScript comes in handy, allowing you to add interactivity to the form.

In this tutorial, we’ll show you how to use JavaScript to handle form submissions by calling a function when the form is submitted.

Step1: Create the HTML Form

First, let’s start with the HTML form. We will create a simple form that contains an input field for the user’s name and a submit button.

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

Note that we have added an id attribute to the form element. This will allow us to reference the form in our JavaScript code later.

JavaScript Function

Next, we need to create a JavaScript function that will be called when the form is submitted. The function will take an event object as its parameter, which will allow us to prevent the default form submission behavior.

function handleSubmit(event) {
  event.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);
    });
}

The function starts by calling event.preventDefault() to prevent the form from being submitted in the default way, which would cause a page refresh.

Then, the function gets a reference to the form element with the id of "myform" using document.getElementById("myform") and assigns it to the variable myform.

Next, it creates a new FormData object, passing in the myform element as an argument. This object contains the form data that will be sent to the server.

The fetch function is then called to make a network request to the URL “https://show.ratufa.io/json" using the HTTP method “POST”. The FormData object is passed as the request body using the body option.

If the network request is successful and the response from the server has a 200 status code, the response body is returned as JSON using the response.json() method. If the response has a different status code, an error is thrown.

If the response is successfully parsed as JSON, the function creates a new pre element using document.createElement("pre"). It then sets the innerHTML of the pre element to the response JSON stringified with two spaces for indentation using JSON.stringify(resp, null, 2). The myform element is then replaced with the pre element using myform.replaceWith(respdiv). Finally, the response is logged to the console using console.log("resp from server ", resp).

If there is an error during the network request or parsing of the response JSON, the error is caught and logged to the console using console.log("error ", error).

Attaching the Function to the Form

Now that we have our HTML form and JavaScript function, we need to attach the function to the form so that it is called when the form is submitted.

We can do this by using the addEventListener() method to add an event listener to the form. We will listen for the submit event, which will be triggered when the user clicks the submit button.

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

myform.addEventListener("submit", submitForm);

Full Demo

Try the full demo here:

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

How to create the server-side script that receives the form submissions

Even though you have completed your form with a button to submit the form, you still need a server-side script that will receive the form submission and perhaps sends you an email and saves the form data to a database for record keeping.

The easier solution is to use a service like Ratufa.io. With Ratufa.io, you don’t need any PHP script or worry about configuring PHP email or SMTP. All you need to do is copy just one line of code to your HTML page and get full backend support for your form instantly.

Pro Tip: Attach a form handler with just one line of code

Ratufa is a form back-end as service. You just have to add one line of code to your form page and the form immediately becomes fully functional.

See a quick demo here:

See Also