Open In App

How to submit a form by clicking a link in JavaScript ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn how to submit a form by clicking a link in JavaScript.

Approach

  • HTML Structure:
    • Basic HTML structure with a title, heading, and a form to submit details.
    • The form contains input fields for Name, Age, and City.
  • JavaScript Function:
    • submitForm() function triggered by clicking “Submit Here.”
    • Retrieves the form by its ID and submits it.
  • Output:
    • Users enter details in the form.
    • Clicking “Submit Here” triggers form submission.

Example: In this example, we have followed the above approach.

HTML




<!DOCTYPE html>
<html>
 
<body>
    <h2 style="color:green">GeeksforGeeks</h2>
    <b>Submit form details</b>
 
    <form id="form__submit" action="form.php" method="post">
        <label>NAME: </label><br />
        <input type="text" name="name" /><br />
        <label>AGE: </label><br />
        <input type="number" name="age" /><br />
        <label>CITY: </label><br />
        <input type="text" name="city" /><br /><br />
        <a href="#" onclick="submitForm()">Submit Here</a>
    </form>
 
    <script>
        function submitForm() {
            let form = document.getElementById("form__submit");
            form.submit();
        }
    </script>
</body>
 
</html>


Note: The given HTML code will redirect the form data to the site or file which is mentioned in the action attribute.

PHP Code: Create a PHP file to get the user entered form data, rename this PHP file as “form.php”. This code displays the user form data.

PHP




<?php
    $name=$_POST['name'];
    $age=$_POST['age'];
    $city=$_POST['city'];
 
    echo "NAME-SUBMITTED : $name <br>";
 
    echo "AGE-SUBMITTED :  $age <br>";
 
    echo "CITY-SUBMITTED:  $city";
?>


Output:

user form data

PHP is a server-side language. So it requires a server. Please refer PHP tutorial for a better understanding.



Last Updated : 22 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads