What is the best way to reload or return to the page after submitting a form?

I am creating a simulated contact form that does not actually send messages. I aim to achieve the effect of refreshing the page upon submitting, giving the appearance that the message has been sent. While my preference is to accomplish this without JavaScript, any suggestions involving JavaScript are also welcome. Below is the code for my contact form:

http://jsfiddle.net/egndc24s/1/

<!DOCTYPE html> <html> <head> <title></title> </head> <body> <div class="container"> <section class="section1"> <div class="sec1title"> <h1>Get in touch</h1> </div> </section> <section class="section2"> <div class="contactform"> <h5>Drop us a line...</h5> <form action="#"> <label for="firstname"><i class="cntfrmicn fa fa-user"></i> <input class="form-fields" name="firstname" type="text"></label> <label for="email"><i class="cntfrmicn fa fa-envelope"></i> <input class="form-fields" name="email" type="text"></label> <label for="contact"><i class="cntfrmicn fa fa-phone"></i> <input class="form-fields" name="contact" type="text"></label> <label for="textarea"><i class="cntfrmicn fa fa-comment"></i> <textarea class="form-fields" cols="30" id="" name="textarea" rows="10"></textarea></label> <button class="form-fields button" type="submit" value="Send">Send <i class="fa fa-paper-plane"></i></button> </form> </div> <script src='https://maps.googleapis.com/maps/api/js?v=3.exp'> </script> <div class="contmap" style='overflow:hidden;height:550px;width:100%;'> <div id='gmap_canvas' style='height:100%;width:100%;'></div> <div> <small><a href="http://embedgooglemaps.com">embed google maps</a></small> </div> <div> <small><a href="http://freedirectorysubmissionsites.com/">free web directories</a></small> </div> <style> #gmap_canvas img{max-width:none!important;background:none!important} </style> </div> <script type='text/javascript'> function init_map(){var myOptions = {zoom:14,center:new google.maps.LatLng(-37.898677,144.640630),mapTypeId: google.maps.MapTypeId.ROADMAP};map = new google.maps.Map(document.getElementById('gmap_canvas'), myOptions);marker = new google.maps.Marker({map: map,position: new google.maps.LatLng(-37.898677,144.640630)});infowindow = new google.maps.InfoWindow({content:'<strong>My Location<\/strong><br>Eagle Stadium<br>'});google.maps.event.addListener(marker, 'click', function(){infowindow.open(map,marker);});infowindow.open(map,marker);}google.maps.event.addDomListener(window, 'load', init_map); </script> </section> </div> </body> </html>

\\\\\\

* { margin:0px; padding:0px; } *, *:after, *:before { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; -ms-box-sizing:border-box; -o-box-sizing:border-box; box-sizing: border-box; } .clearfix:before, .clearfix:after { display: table; content: ''; } .clearfix:after { clear: both; } body { background: #1c1c1c; color: #333; font-weight: normal; font-size: 1em; font-family: 'Roboto', Arial, sans-serif; } input:focus, textarea:focus, keygen:focus, select:focus { outline: none; } ::-moz-placeholder { color: #666; font-weight: 300; opacity: 1; } ::-webkit-input-placeholder { color: #666; font-weight: 300; } /* contact from design */ .container { padding: 20px 50px 70px; } .sec1title { text-align: center; } .sec1title h1 { font-size: 40px; margin: 25px; text-transform: uppercase; color: red; font-weight: 400; } .section2 { position: relative; overflow: hidden; } .section2 .contactform { position: absolute; top: 0; right: 10%; z-index: 99; background: #393939; padding: 30px 40px 70px; box-sizing: border-box; } .section2 .contactform input.form-fields, .section2 .contactform button.form-fields, .section2 .contactform textarea.form-fields { padding: 0 0 0 40px; display: block; box-sizing: border-box; width: 350px; font-size: 16px; background: #323232; margin: 7px 0; border: 1px solid #00C1A8; color: #6BECDB; opacity: 0.5; min-height: 45px; text-shadow: none; position: relative; } .section2 .contactform textarea.form-fields { padding: 8px 40px; resize: none; } .section2 .contactform button.form-fields.button { color: #16F1D4; font-size: 14px; padding: 0; text-transform: uppercase; } .section2 .contactform button.form-fields.button:hover { background: #00C1A8; color: #fff; cursor: pointer; opacity: 1; } .section2 .contactform button.form-fields.button i { margin-left:10px; } .section2 .contactform h5 { color: #16F1D4; font-size: 16px; margin-bottom: 15px; } .section2 .contactform label .cntfrmicn { color: #00C1A8; padding: 14px; position: absolute; z-index: 99; } @media only screen and (max-width: 660px) { .container { padding: 10px 20px 30px; } .contmap { height: 475px !important; } .sec1title h1 { font-size: 28px; } .section2 .contactform { padding: 10px; right: 0; width: 100%; } .section2 .contactform input.form-fields, .section2 .contactform button.form-fields, .section2 .contactform textarea.form-fields { width: 100%; } }

Answer №1

To make the form's submit button refresh the page, you can set its onClick event handler to either location.reload() or location = location (in case of older browsers).

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <div class="container">
        <section class="section1">
            <div class="sec1title">
                <h1>Contact Us</h1>
            </div>
        </section>
        <section class="section2">
            <div class="contactform">
                <h5>Drop us a message...</h5>
                <form action="#">
                    <label for="firstname"><i class="cntfrmicn fa fa-user"></i> <input class="form-fields" name="firstname" type="text"></label> <label for="email"><i class="cntfrmicn fa fa-envelope"></i> <input class="form-fields" name="email" type="text"></label> <label for="contact"><i class="cntfrmicn fa fa-phone"></i> <input class="form-fields" name="contact" type="text"></label> <label for="textarea"><i class="cntfrmicn fa fa-comment"></i> 
                    <textarea class="form-fields" cols="30" id="" name="textarea" rows="10"></textarea></label> <button class="form-fields button" type="submit" value="Send" onClick="refreshPage()">Send <i class="fa fa-paper-plane"></i></button>
                </form>
            </div>
            <script src='https://maps.googleapis.com/maps/api/js?v=3.exp'>
            </script>
            <div class="contmap" style='overflow:hidden;height:550px;width:100%;'>
                <div id='gmap_canvas' style='height:100%;width:100%;'></div>
                <div>
                    <small><a href="http://embedgooglemaps.com">embed google maps</a></small>
                </div>
                <div>
                    <small><a href="http://freedirectorysubmissionsites.com/">free web directories</a></small>
                </div>
                <style>
                                                    #gmap_canvas img{max-width:none!important;background:none!important}
                </style>
            </div>
            <script type='text/javascript'>
            function refreshPage(){
               console.log("Refreshing page");
               location.reload ? location.reload() : location = location;
           }
            </script>
        </section>
    </div>
</body>
</html>

Answer №2

Which specific endpoint in your backend is responsible for processing the form data?

If the endpoint is the same as the current page's URL, the browser will automatically refresh it after form submission.

<form action="">

If the endpoint is different, consider redirecting back to this page either using server-side or client-side logic.

Another approach involving JavaScript would be to make an AJAX request and include onsubmit="location.reload(true)" within the form tag.

Learn more about the onsubmit event here

Explore how to use location.reload() method here

Answer №3

My solution: - for the return button:

                                                            <button onclick="window.history.go(-1); return false;">Go Back</button>

using javascript:

$(document).ready(function(e){
    if(window.history.replaceState){
      window.history.replaceState( null, null, window.location.href );
    }
  
    /*Retrieve data in case of back or forward navigation*/
    const [entry] = performance.getEntriesByType("navigation");
    if (entry["type"] === "back_forward"){
      const sugSearchId = localStorage.getItem("sugSearchId");
      const sugSearchIdContent = localStorage.getItem("sugSearchIdContent");
      const sugState = localStorage.getItem("sugState");
      const sugType = localStorage.getItem("sugType");
      const sugSearchText = localStorage.getItem("sugSearchText");
      const searchDateFrom = localStorage.getItem("searchDateFrom");
      const searchDateTo = localStorage.getItem("searchDateTo");
      const pageSelected = localStorage.getItem("pageSelected");
      $('#sugSearchId').val(sugSearchId);
      $('#sugSearchIdContent').val(sugSearchIdContent);
      $('#sugState').val(sugState);
      $('#sugType').val(sugType);
      $('#sugSearchText').val(sugSearchText);
      $('#searchDateFrom').val(searchDateFrom);
      $('#searchDateTo').val(searchDateTo);
      $('#pageSelected').val(pageSelected);
      $('#searchForm').submit(); 
    }

    /*Submit action with storage*/
    $(document).on("click","#buttonSubmit",function(){
         localStorage.setItem("sugSearchId", $("#sugSearchId").val());
         localStorage.setItem("sugSearchIdContent", $("#sugSearchIdContent").val());
         localStorage.setItem("sugState", $("#sugState").val());
         localStorage.setItem("sugType", $("#sugType").val());
         localStorage.setItem("sugSearchText", $("#sugSearchText").val());
         localStorage.setItem("searchDateFrom", $("#searchDateFrom").val());
         localStorage.setItem("searchDateTo", $("#searchDateTo").val());
         localStorage.setItem("pageSelected", 1);
      });   
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Customizing tooltip text in Google Chart API: A step-by-step guide

http://code.google.com/apis/chart/ <script type="text/javascript" src="https://www.google.com/jsapi"></script> <script type="text/javascript"> // Loading the Visualization API and the piechart package from Google. google.load(' ...

How to Execute a Class Function from a Different File in React by Clicking a Button in

I have integrated a chart on my website with an interactive feature that allows an object to be displayed by pressing a key in the chart.js file. I now want to replicate this functionality using a button click instead. chart.js ... onKeyPress(e) { c ...

How to Incorporate External PHP into JSP Without Using iFrames

I'm facing a dilemma while working on a website I manage. The task at hand involves adding a report to a JSP page that pulls data from a MySQL database. Unfortunately, connecting the JSP to the database would require additional code functions that I d ...

Struggling to retrieve a particular user using ExpressJs due to an error

Looking to retrieve a specific user in ExpressJS from a JSON file. Encountering this error message: UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client This is the snippet of code being u ...

Save the currently active index of the mySwiper element even after the page is

After clicking through the carousel, I want to be able to store the current index and slide back to it after a page refresh. Is there a way to save this value in a variable so that I can use the mySwiper.slideTo() method to return to the last index? In si ...

Exploring file serving in Node.js with passport authentications

I am currently utilizing Passport with the Google strategy for authentication. Here is my folder structure: views home.html enter.html (this contains just one Google+ button) app.js routes auth.js (handles Google login) I want the client to be direc ...

Excluding numerical values from an array using JavaScript

I have been working on a code snippet to filter out numeric values from an array, but instead of getting only the numbers, I am receiving the complete array. I am unable to identify where the issue lies in my code. Can someone please assist me as I am cu ...

A step-by-step guide on implementing the bliss view engine in Express.js instead of Jade

Is there a way to utilize the bliss view engine instead of the typical jade engine in Express JS? I came across an article on Stack Overflow, but it seems to be geared towards an older version of express.js. I am using version 3.x. Specifically, I am int ...

Is it possible to convert an object and/or a nested array with objects into a JSON string without relying on JSON.stringify?

Struggling to generate a correct JSON string from an object without relying on JSON.stringify(). Presenting my current implementation below - var my_json_encode = function(input) { if(typeof(input) === "string"){ return '"'+input+&apo ...

typescriptWhat is the syntax in TypeScript for creating a prototype of a multidimensional

I'm currently working on implementing additional methods for a 2D array using TypeScript. Adding methods to a 1D array is straightforward, as shown below: interface Array<T> { randomize(); } Array.prototype.randomize = function () { ...

The debate between client-side and server-side video encoding

My knowledge on this topic is quite limited and my Google search didn't provide any clear answers. While reading through this article, the author mentions: In most video workflows, there is usually a transcoding server or serverless cloud function ...

Unlocking the secret to accessing state in a JavaScript file using VUEX

Can anyone help me figure out why I can't access the currentUser property from the state in my vuex store's user.js file? I'm trying to use it in auth.js, but when I write: store.state.currentUser.uid === ... This is the error message I&apo ...

How can I show a Spinner component overlay in a TextField, replacing the usual iconProps rendering the icon in Fluent UI?

I am looking for a way to conditionally display the Spinner component in the exact location where an icon would normally appear if passed to iconProps in TextField. I have managed to implement conditional rendering of the icon and spinner, but incorporat ...

Unexpected alteration of property value when using methods like Array.from() or insertAdjacentElement

I'm encountering an issue where a property of my class undergoes an unintended transformation. import { Draggable, DragTarget } from '../Models/eventlisteners'; import { HeroValues } from '../Models/responseModels'; import { Uti ...

Different ways to toggle multiple images using jQuery on various button clicks

After spending some time on my code, I have come across a peculiar issue. I am working with 4 black and white images and corresponding buttons that toggle them to color when clicked. The problem arises when I click one button after another - the previousl ...

ways to display view without page refresh in mvc3

@using (Html.BeginForm("Index", "HRBankInfo", FormMethod.Get)) { <div align="center" class="display-label"> @ViewBag.message <br /><input type="submit" value="Ok" /> </div> } This particular partial view is display ...

Create a screen divided into two separate sections using horizontal split dividers

Trying to figure out how to set a div in HTML and then have a second div take up the remaining space. It seems like it should be simple, but I'm struggling with it. I'd like to have a div with a fixed height and then have another div take up the ...

Hide only the table that is being clicked on, not all tables

Essentially, I am using document.querySelectorAll() to retrieve an array of div elements. In my function, handleClick(), each time the button is clicked, I want to hide the table associated with that specific button. This is the current situation: https:/ ...

Angular and the dynamic transformation of the DOM tree through an array

I am using an HTML component within Angular. The template code looks like this: <tr ng-repeat="item in documentList track by $index"> <td>{{item.TYPE}}</td> <td>{{item.DATE_CRE ...

What is the most effective way to use checkboxes to apply multiple filters to an array of objects?

Let me simplify the description. Within the App component, I fetch data from a JSON file and store it in the flightsList array. My goal is to filter this array based on checkboxes selected in the FlightOptions and Airlines components. The issue that I&a ...